<?php
/**
 * Copyright (c) 2018. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/**
 * 分拣配货API
 * User: rui
 * Email: poptser@foxmail.com
 * Date: 2016/10/10
 * Time: 14:59
 */

namespace SDXApi\Controller;
use Com\Baidushipping\BaidushippingSubmit;
use Com\Elemeshipping\ElemeshippingSubmit;
use Com\Gkshipping\GkshippingSubmit;
use Com\Sdxbsc\SdxbscSubmit;
use Com\Sfshipping\SfshippingSubmit;
use SDXApi\Service\KingdeeService;
use Think\Exception;
use Think\Model;
use Common\Api\Ali_ossApi;
use Think\Log;

class SortingController extends AppController
{
    public $redis;

    public function _initialize($apptoken = '', $apptime = '', $check_uid = false, $session_id = '', $check_sign = true)
    {
        parent::_initialize($apptoken, $apptime, $check_uid, $session_id, false);

        $warehouse_personnel=M('warehouse_personnel');
        $user_id=I('post.user_id','intval');
        $wprow=$warehouse_personnel->field('position,wid,longitude,latitude,status')->where(array('uid'=>$user_id,'position'=>1))->find();
        if(!$wprow){
            //returnApiError("无此操作权限");
        }


        $this->redis = new \Redis();
        $this->redis->connect('47.106.126.134','6379');
        $this->redis->auth('SDX2017best');
        $this->redis->select('4');
    }

    /**
     * 根据用户ID获取仓库ID
     * rui poptser@foxmail.com 2016-10-10 10:09:19
     * @param $user_id
     */
    private function get_user_wid_identity($user_id){
        //$user_wid = S("swid_".$user_id);
        if(empty($user_wid)){
            $user_wid = M("warehouse_personnel")->where(array("uid"=>$user_id))->getField("wid");
            //S("swid_".$user_id,$user_wid);
            //dump(M("warehouse_personnel")->getLastSql());
        }
        return $user_wid;
    }

    /**
     * 获取地址信息
     * rui poptser@foxmail.com 2016-10-11 09:30:20
     * @param $country
     * @param $province
     * @param $city
     * @param $district
     * @return string
     */
    private function get_address_desc($country, $province, $city, $district){
        $country_name=A("Distribution")->get_region_name($country);
        $province_name=A("Distribution")->get_region_name($province);
        $city_name=A("Distribution")->get_region_name($city);
        $district_name=A("Distribution")->get_region_name($district);
        return $country_name.$province_name.$city_name.$district_name;
    }

    /**
     * 检查提交账号是否为配货账号
     * rui poptser@foxmail.com 2016-10-11 10:09:19
     * @param $user_id
     */
    private function check_user($user_id){
        $wp=A("Distribution")->check_warehouse_personnel($user_id,1);
        if(!$wp){
            returnApiError('无此用户/禁用');
            exit();
        }
    }


    /**
     * 修改订单为配货中
     * rui poptser@foxmail.com 2016-10-11 10:09:19
     * @param $user_id
     * @param $order_id
     */
    private function deploy_order_action($user_id,$order_id,$wid,$is_r=false){
        //returnApiError("已暂停使用此功能，请使用新版拣货端");
        $where = "outgo = 0 and order_id = ".$order_id." AND wid = ".$wid;
        $where .= " AND sorting_id = 0 AND order_status !=2 AND pay_status in(2,3)";
        $where .= " AND (is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1))";
        //$where .= " AND shipping_status = 0 AND 196_admin_id = 0";
        $where .= " AND shipping_status in(0,3) AND k3cn_sn IS NULL";
        //$where .= " AND ((shipping_status = 0 AND shipping_id = 3) OR (shipping_status = 1 AND shipping_id = 2))";

        $data['sorting_id'] = $user_id;
        $data['shipping_status'] = 3;   //修改为配货中
        if($is_r){
            $data['is_random'] = 1;
        }
        $result = M("order_info")->where($where)->save($data);    //修改订单信息表中的  sorting_id  开始配货

        if($result){
            //修改成功，写入日志
            $order_info = M("order_info")->where("order_id = ".$order_id)->find();
            $a=array(
                'order_id'=>$order_id,
                'user_id'=>$user_id,
                'order_status'=>$order_info['order_status'],
                'shipping_status'=>3,
                'pay_status'=>$order_info['pay_status'],
                'to_user'=>1,
                'action_note'=>'开始配货'
            );

            A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
            A("Distribution")->record_logistics($order_id,3,"开始配货");
            return true;
        }else{
            $order_info = M("order_info")->where("order_id = ".$order_id)->find();

            if($order_info['outgo']!=0) returnApiError("未回仓订单，无法开始配货");

            if($order_info['k3cn_sn']!="") returnApiError("金蝶订单，请使用新版本");

            if($order_info['wid']!=$wid) returnApiError("非本仓库订单,此单属于仓库:{$order_info['wid']},{$order_info['order_sn']}");

            if($order_info['sorting_id']!=0) returnApiError("已在配货中{$order_info['order_sn']}");

            if($order_info['shipping_status']!=0 && $order_info['shipping_status']!=3) returnApiError("订单不在未发货状态{$order_info['order_sn']}");

            if($order_info['order_status']==2) returnApiError("订单已被取消{$order_info['order_sn']}");

            if($order_info['pay_status']!=2 && $order_info['pay_status']!=3) returnApiError("订单还未支付{$order_info['order_sn']}");

            if($order_info['is_presell'] ==1 && $order_info['buckle_inventory'] ==0 ) returnApiError("预售单无法配货{$order_info['order_sn']}");

            return false;
        }
    }

    /**
     * TODO 订单下商品列表（返回用）
     * rui poptser@foxmail.com 2016-11-22 15:32:01
     */
    public function sh_goods_list($order_id,$wid,$only_goods_id = false){
        $rui_goods_list = array();
        $goods_list = $this->get_goods_list_real($order_id);

        if($only_goods_id){
            return $goods_list;
        }

        //dump($goods_list);
        if(count($goods_list)>0){
            foreach ($goods_list as $key=>$value){
                $goods_data = M("goods")->where(array("goods_id"=>$value['goods_id']))->find();
                $goods_lists['count'] = $value['real_num'];     //数量
                $goods_lists['goods_id'] = $value['goods_id'];     //
                //dump($value['giving']);

                $goods_lists['name'] = $value['goods_name'];    //商品名
                switch ($value['giving']){
                    case 1:
                        $goods_lists[$key]['goods_name'] .=" [ 赠品 ] ";
                        break;
                    case 2:
                        $goods_lists[$key]['goods_name'] .=" [ 换购 ] ";
                        break;
                    case 3:
                        $goods_lists[$key]['goods_name'] .=" [ 抢购 ] ";
                        break;
                    case 4:
                        $goods_lists[$key]['goods_name'] .=" [ 促销 ] ";
                        break;
                }


                //$goods_lists['shop_remark'] = $value['goods_price'];  //价格
                $goods_lists['price'] = $value['goods_price'];  //价格
                $goods_lists['act_id'] = $value['act_id'];  //活动ID
                $goods_lists['rec_id'] = $value['rec_id'];  //活动ID
                $goods_lists['giving'] = $value['giving'];  //  商品类型
                $goods_lists['id'] = $value['goods_id'];        //商品ID
                $goods_lists['shop_remark'] = $goods_data['seller_note'];    //商家备注
                $goods_lists['goods_number'] = preg_replace('/[^0-9a-zA-Z]+/','',$value['goods_sn']);      //货号
                $store_count = M("goods_storage")->where("goods_id =".$value['goods_id']." AND wid = ".$wid)->find();
                $goods_lists['store_count'] = "实：".$store_count['practical_num']." 冻：".$store_count['freeze_num']; //库存
                $goods_lists['p_store_count'] = $store_count['practical_num']; //库存
                $goods_lists['d_store_count'] = $store_count['freeze_num']; //库存
                $goods_lists['goods_category'] = M("category")->where(array("cat_id"=>$value['cat_id']))->getField('cat_name'); //分类名

                //货架信息
                $model = M();
                $sql = "SELECT sh.*,sc.name AS shelf_tag,sl.name AS shelf_type,wh.name AS shelf_store,sg.sh_floor AS putaway_row,
                sh.shelves_sn AS shelf_num
                FROM sdx_shelves AS sh,sdx_shelves_cat AS sc,sdx_shelves_class AS sl ,sdx_warehouse AS wh,sdx_shelves_goods AS sg
                WHERE sh.state = 1 AND 
                sh.category_id = sc.id AND sh.class_id = sl.id AND sh.wid =  wh.id AND sg.sh_id = sh.id AND sh.wid = '".$wid."' 
                AND sg.goods_sn = '".$value['goods_sn']."'";
                $goods_shelves = $model->query($sql);
                if($goods_shelves){
                    $goods_lists['shelf_info'] = "";
                    foreach ($goods_shelves as $vaule){
                        $goods_lists['shelf_info'] .= $vaule['shelf_tag']."->".$vaule['shelf_type']."[ ".$vaule['shelf_num']."-".$vaule['putaway_row']." ]\n";
                    }


                    $goods_lists['shelf_sort'] = $goods_shelves[0]['sort']+$goods_shelves[0]['putaway_row']/100;
                }else{
                    $goods_lists['shelf_info'] = "无货架信息";
                    $goods_lists['shelf_sort'] = "999999";
                }

                $goods_lists['goods_img'] = $goods_data['goods_img'];    //商品图片
                $goods_lists['original_img'] = $goods_data['original_img']; //商品缩略图

                $goods_lists['price_member'] = D('goods')->get_vip_price_for_all($value['goods_id'],1); //注册会员价
                $goods_lists['price_vip']    = D('goods')->get_vip_price_for_all($value['goods_id'],2); //VIP会员价



                array_push($rui_goods_list,$goods_lists);
            }
            return $rui_goods_list;
        }else{
            return false;
        }
    }

    /**
     * TODO 订单下退款商品列表（返回用）
     * @param $order_id
     * @param $wid
     * @return array|bool
     */
    public function re_goods_list($order_id, $wid){
        $goods_list = $this->get_refund_goods_list($order_id);

        if(count($goods_list)>0){
            $rui_goods_list = array();
            foreach ($goods_list as $key=>$value){
                $goods_data = M("goods")->where(array("goods_id"=>$value['goods_id']))->find();
                $goods_lists['count'] = $value['refund_number'];
                $goods_lists['name'] = $value['goods_name'];
                switch ($value['giving']){
                    case 1:
                        $goods_lists[$key]['goods_name'] .=" [ 赠品 ] ";
                        break;
                    case 2:
                        $goods_lists[$key]['goods_name'] .=" [ 换购 ] ";
                        break;
                    case 3:
                        $goods_lists[$key]['goods_name'] .=" [ 抢购 ] ";
                        break;
                    case 4:
                        $goods_lists[$key]['goods_name'] .=" [ 促销 ] ";
                        break;
                }
                $goods_lists['giving'] = $value['giving'];  //  商品类型
                $goods_lists['price'] = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField('shop_price');
                $goods_lists['id'] = $value['goods_id'];
                $goods_lists['shop_remark'] = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField('seller_note');    //商家备注
                $goods_lists['goods_number'] = $value['goods_sn'];
                $store_count = M("goods_storage")->where("goods_id =".$value['goods_id']." AND wid = ".$wid)->find();
                $goods_lists['store_count'] = "实：".$store_count['practical_num']." 冻：".$store_count['freeze_num'];
                $goods_lists['goods_category'] = M("category")->where(array("cat_id"=>$value['cat_id']))->getField('cat_name');

                //货架信息
                $model = M();
                $sql = "SELECT sh.*,sc.name AS shelf_tag,sl.name AS shelf_type,wh.name AS shelf_store,sg.sh_floor AS putaway_row,
                sh.shelves_sn AS shelf_num
                FROM sdx_shelves AS sh,sdx_shelves_cat AS sc,sdx_shelves_class AS sl ,sdx_warehouse AS wh,sdx_shelves_goods AS sg
                WHERE 
                sh.category_id = sc.id AND sh.class_id = sl.id AND sh.wid =  wh.id AND sg.sh_id = sh.id
                AND sg.goods_sn = '".$value['goods_sn']."'";
                $goods_shelves = $model->query($sql);
                if($goods_shelves){
                    $goods_lists['shelf_info'] = "";
                    foreach ($goods_shelves as $vaule){
                        $goods_lists['shelf_info'] .= $vaule['shelf_tag']."->".$vaule['shelf_type']."[ ".$vaule['shelf_num']."-".$vaule['putaway_row']." ]\n";
                    }
                }else{
                    $goods_lists['shelf_info'] = "无货架信息";
                }
                $goods_lists['goods_img'] = $goods_data['goods_img'];    //商品图片
                $goods_lists['original_img'] = $goods_data['original_img']; //商品缩略图

                $goods_lists['price_member'] = D('goods')->get_vip_price_for_all($value['goods_id'],1); //注册会员价
                $goods_lists['price_vip']    = D('goods')->get_vip_price_for_all($value['goods_id'],2); //VIP会员价

                array_push($rui_goods_list,$goods_lists);
            }
            return $rui_goods_list;
        }else{
            return false;
        }
    }

    /**
     * TODO 获取订单详情
     * @param $result
     * @return mixed
     */
    public function get_order_info($result){
        $result['address'] = str_replace($result['sign_building'],"",$result['address']);
        $result['address'] = $this->get_address_desc($result['country'], $result['province'], $result['city'], $result['district']) . $result['address'] ." [ ". $result['sign_building'] ." ] ". $result['address_name'];
        $result['order_time'] = local_date('Y-m-d H:i:s', $result['order_time']);
        $deploy_info = A("Distribution")->get_admin_user_name($result['sorting_id']);
        $distribute_info = A("Distribution")->get_admin_user_name($result['wp_userid']);
        $quality_info = A("Distribution")->get_admin_user_name($result['quality_id']);
        $result['deploy_name'] = $deploy_info['user_name']; //配货员姓名
        $result['deploy_phone'] = $deploy_info['phone']; //配货员手机号码
        $result['distribute_name'] = $distribute_info['user_name']; //配送员姓名
        $result['distribute_phone'] = $distribute_info['phone']; //配送员手机号码
        $result['quality_name'] = $quality_info['user_name']; //配送员手机号码
        $result['quality_phone'] = $quality_info['phone']; //配送员手机号码
        $result['order_remark']=$result['postscript']; //订单备注
        $result['shop_remark'] =   $result['to_buyer']; //商家备注

        $result['free_single'] = M("order_info_free_single")->
        where(array("order_id"=>$result['order_id']))->count();

        if($result['batch_no']>0){
            $order_where_sub = "batch_no =".$result['batch_no']." AND TO_DAYS(from_unixtime(best_time)) = TO_DAYS(from_unixtime(".$result['best_time']."))";
            $order_num=M("order_info")->where($order_where_sub)->count(); //查询是否有分单
            if($order_num>1){
                $result['sub']= 1;
            }else{
                $result['sub']= 0;
            }
        }else{
            $result['sub']= 0;
        }


//        if($result['shipping_id']==2){
//            $result['order_num'] = $result['order_num']." 「 自提单 」";
//        }
        if($result['quality_id']>0){
            $result['isCheck'] = 1;
        }else{
            $result['isCheck'] = 0;
        }

        $result['weight']=$this->get_order_weight($result['order_id']); //订单重量
        $result['order_want_time']=date('Y-m-d H:i:s',$result['best_time_start'])."\n".date('Y-m-d H:i:s',$result['best_time']); //预期送达时间
        $result['order_area']=M("warehouse_deliver_region")->where(array("id"=>$result['wdr_id']))->getField('name'); //配货区域
        $result['order_store']=M("warehouse")->where(array("id"=>$result['wid']))->getField('name'); //配货区域
        //订单操作记录
        $where= "order_id = ".$result['order_id']." and (action_user not like '%[%' and action_user !='buyer' )and action_note !=''";
        $order_action = M("order_action")->where($where)->select();
        //dump(M("order_action")->getLastSql());

        foreach ($order_action as $value){
            $result['action_remark'] .=$value['action_user']."  ".$value['action_note']."<br/>";
        }

        $user_tag = M()->field('k.name,v.value')->
        table('sdx_user_tag_value as v,sdx_user_tag_key as k')->
        where('v.key_id = k.id and v.uid ='.$result['user_id']." and v.address_id =".$result['address_id'])->select();
        if($user_tag){
            foreach ($user_tag as $value){
                $result['member_tag'] .=$value['name'].":".$value['value']."\n";
            }
        }


        $first_order = M("order_info")->where("order_status !=2 AND 
                    pay_status IN (2,3) AND user_id = {$result['user_id']}")->order("order_id asc")->getField("order_id");
        if($first_order==$result['order_id']){
            $result['first_order'] = 1;
        }else{
            $result['first_order'] = 0;
        }

        return $result;
    }

    /**
     * TODO 获取订单重量
     * @param $order_id
     * @return int
     */
    public function get_order_weight($order_id){
        $order_weight = 0;
        $goods_list = $this->get_goods_list_real($order_id);
        foreach ($goods_list as $value){
            $goods_weight = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField('goods_weight');
            $one_good_weight = $goods_weight*$value['real_num'];
            $order_weight +=$one_good_weight;
        }
        return $order_weight;   //返回本订单总量（单位KG）
    }


    /**
     * 配货中列表
     * rui poptser@foxmail.com 2016-10-10 16:10:29
     */
    // TODO 配货中列表 deploy_list
    public function deploy_list(){
        $user_id=I('post.user_id','intval');
        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);
        //$wid = 8;
        $order_info = M("order_info");

        $page=I('post.page','intval');
        $where['sorting_id']=$user_id;
        $where['pay_status']=array('in','2,3');
        $where['order_status']= array('neq',2);
        $where['shipping_status']= array('in','0,3');	//备货中
        $where['wid']=$wid;
        //$where['196_admin_id']=0;

        $group_order = M("sorting_order_group")->where("state = 0 AND user_id = ".$user_id)->getField("order_id",true);

        $group_order_array = array();

        foreach ($group_order as $value){
            $value = array_filter(array_unique(explode(",",$value)));

            array_merge($group_order_array,$value);
        }


        if(count($group_order_array)>0){
            $where['order_id'] = array('not in',$group_order_array);
        }
        $company_array = M("distribution_company_user")->where(array("user_id"=>$user_id))->getField("company_id",true);
        if(!empty($company_array)){
            $where_tow['distribution_company_id'] = array("in",$company_array);
        }

        $where_tow['pay_status'] = array('IN','2,3');
        $where_tow['order_status'] = array('neq',2);
        $where_tow['wid'] = $wid;
        $where_tow['sorting_id'] = array('neq',0);

        $where_tow['outgo']=0;	    //商品未出仓


        $where_tow['shipping_status'] = 5;	//配货完成
        $where_tow['quality_id'] = 0;	    //未质检
        $count_examine=$order_info->where($where_tow)->count();
        //dump($order_info->getLastSql());

        unset($where_tow['quality_id']);
        $where_tow['sorting_id'] = 0;
        $where_tow['shipping_status'] = array('in','0,3');

        $where_tow['_string'] = "(is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1))";
        if($page==999){
            $list=$order_info->field('distribution_company_id,shipping_id,to_buyer,quality_id,address_id,user_id,batch_no,outgo,sorting_id,wp_userid,wid,wdr_id,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                ->where($where)->order('order_id desc')->select();
        }else{
            $count_unpicking=$order_info->where($where_tow)->count();
            $ssq=$wid;

            $count=$order_info->where($where)->count();
            if($count==0){
                returnApiSuccess(array('list'=>array(),'is_last'=>1,
                    'count_prepare'=>0,'count_unpicking'=>$count_unpicking,
                    'ssq'=>$ssq,
                    'count_examine'=>$count_examine
                ),'无数据');
            }
            $pagearr=show_page($count, $page);
            if($page>=$pagearr['pagecount']){
                $is_last=1;
            }else{
                $is_last=0;
            }

            $list=$order_info->field('distribution_company_id,shipping_id,to_buyer,quality_id,address_id,user_id,batch_no,outgo,sorting_id,wp_userid,wid,wdr_id,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                ->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('order_id desc')->select();
        }

        if($list){
            $push_array = array();
            foreach ($list as $k=>$v){
                unset($one_order);

                $one_order = $this->get_order_info($v);
                $one_order['order_state'] = 1;  //配货中
                $re_goods_list = $this->re_goods_list($v['order_id'],$wid);
                if($re_goods_list){
                    $one_order['goods_list_back']=$re_goods_list;
                }
                $goods_list = $this->sh_goods_list($v['order_id'],$wid);
                if($goods_list){
                    $one_order['goods_list']=$goods_list;
                }
                $cold_data = $this->check_goods($goods_list);
                $one_order['is_cold'] = $cold_data['is_cold'];
                $one_order['is_ice'] = $cold_data['is_ice'];
                $one_order['is_nom'] = $cold_data['is_nom'];
                if($v['quality_id']>0){
                    $one_order['isCheck'] = 1;
                }else{
                    $one_order['isCheck'] = 0;
                }
                array_push($push_array,$one_order);

            }



            returnApiSuccess(
                array(
                    'list'=>$push_array,
                    'is_last'=>$is_last,
                    'ssq'=>$ssq,
                    'count_prepare'=>$count,                //配货中
                    'count_unpicking'=>$count_unpicking,    //未发货
                    'count_examine'=>$count_examine         //未质检
                ),'success');
        }else{
            returnApiError('数据为空');
        }
    }

    /**
     * TODO 检查商品中是否有冷冻冷藏商品
     * @param $goods_list
     * @return mixed
     */
    private function check_goods($goods_list) {

        $re_data['is_cold'] = 0;    //冷冻
        $re_data['is_ice'] = 0;     //冷藏
        $re_data['is_nom'] = 0;     //常温

        foreach ($goods_list as $value){
            if($re_data['is_cold']==0||$re_data['is_ice']==0||$re_data['is_nom']==0){
                $goods_cat_id = M("goods")->where(array("goods_id"=>$value['goods_id']))->field("cat_id,temperature")->find();

                if(empty($goods_cat_id['temperature'])){

                    $cat_id = M("category")->field("parent_id,temperature")->where(array("cat_id"=>$goods_cat_id['cat_id']))->find();

                    if(empty($cat_id['temperature'])&&!empty($cat_id['parent_id'])){

                        $cat_2 = M("category")->field("parent_id,temperature")->where(array("cat_id"=>$cat_id['parent_id']))->find();
                        if(empty($cat_2['temperature'])&&!empty($cat_2['parent_id'])){
                            $cat_3 = M("category")->field("parent_id,temperature")->where(array("cat_id"=>$cat_2['parent_id']))->find();
                            //dump($cat_3);
                            if(!empty($cat_3['temperature'])){
                                if($cat_3['temperature']==2){
                                    $re_data['is_cold'] = 1;
                                }
                                if($cat_3['temperature']==3){
                                    $re_data['is_ice'] = 1;
                                }
                                if($cat_3['temperature']==1){
                                    $re_data['is_nom'] = 1;
                                }
                            }
                        }else{
                            if($cat_2['temperature']==2){
                                $re_data['is_cold'] = 1;
                            }
                            if($cat_2['temperature']==3){
                                $re_data['is_ice'] = 1;
                            }
                            if($cat_2['temperature']==1){
                                $re_data['is_nom'] = 1;
                            }
                        }
                    }else{
                        if($cat_id['temperature']==2){
                            $re_data['is_cold'] = 1;
                        }
                        if($cat_id['temperature']==3){
                            $re_data['is_ice'] = 1;
                        }
                        if($cat_id['temperature']==1){
                            $re_data['is_nom'] = 1;
                        }
                    }
                }else{
                    if($goods_cat_id['temperature']==2){
                        $re_data['is_cold'] = 1;
                    }
                    if($goods_cat_id['temperature']==3){
                        $re_data['is_ice'] = 1;
                    }
                    if($goods_cat_id['temperature']==1){
                        $re_data['is_nom'] = 1;
                    }
                }

            }
        }
        return $re_data;
    }

    /**
     * 配货完成列表
     * rui poptser@foxmail.com 2016-10-10 10:09:19
     */
    // TODO 配货完成列表 deployed_list
    public function deployed_list(){
        $user_id=I('post.user_id','intval');

        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);

        $page=I('post.page','intval');
        $year = I('post.year','intval');
        $month = I('post.month','intval');
        if($year>0 && $month>0){
            $days = date('t', strtotime($year."-".$month));
            $begintime = strtotime($year."-".$month."-1");
            $endtime = strtotime($year."-".$month."-".$days." 23:59:59");
            $where['sorting_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ; //
        }
//        $company_array = M("distribution_company_user")->where(array("user_id"=>$user_id))->getField("company_id",true);
//        if(!empty($company_array)){
//            $where['distribution_company_id'] = array("in",$company_array);
//        }

        $where['sorting_id']=$user_id;
        //$where['196_admin_id']=0;
        $where['pay_status']=array("EGT",2);
        $where['order_status']=array("NEQ",2);
        $where['shipping_status']=array("in","5,1,2");;    //已发货
        $count=M('order_info')->where($where)->count();
    //echo     $sql = M('order_info')->getLastSql();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('order_info')->field('distribution_company_id,shipping_id,quality_id,address_id,user_id,batch_no,outgo,sorting_id,wp_userid,wid,wdr_id,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('sorting_time desc,order_id desc')->select();
        if($list){
            $push_array = array();
            foreach ($list as $k=>$v){
                unset($one_order);

                $one_order = $this->get_order_info($v);
                $one_order['order_state'] = 2;  //配货中

                $re_goods_list = $this->re_goods_list($v['order_id'],$wid);
                if($re_goods_list){
                    $one_order['goods_list_back']=$re_goods_list;
                }
                $goods_list = $this->sh_goods_list($v['order_id'],$wid);
                if($goods_list){
                    $one_order['goods_list']=$goods_list;
                }
                $cold_data = $this->check_goods($goods_list);
                $one_order['is_cold'] = $cold_data['is_cold'];
                $one_order['is_ice'] = $cold_data['is_ice'];
                $one_order['is_nom'] = $cold_data['is_nom'];
                array_push($push_array,$one_order);
                unset($one_order);
            }
            returnApiSuccess(array('list'=>$push_array,'is_last'=>$is_last,'count'=>$count),'success');
        }else{
            returnApiError("已返回全部");
            $list = array();
            $is_last =1;
            $count = 0;
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }
    }

    /**
     * 搜索订单号(可使用订单号/收货人姓名/收货人手机号进行搜索)
     * rui poptser@foxmail.com 2016-10-11 11:00:40
     */
    // TODO 搜索订单 search_order
    public function search_order(){
        $user_id = I('post.user_id','intval');
        $key_words = I('post.key');
        $page=I('post.page','intval');

        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);

        if(empty($key_words)){
            returnApiError("关键字为空");
        }

        //$where = " 196_admin_id = 0 AND
        $where = " k3cn_sn IS NULL AND 
          wid = ".$wid."
          AND (order_sn LIKE '%" . $key_words . "%' OR consignee LIKE '%" . $key_words . "%' OR mobile LIKE '%" . $key_words . "%')";
        $count=M('order_info')->where($where)->count("order_id");
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }

        $list=M('order_info')->field('distribution_company_id,shipping_id,quality_id,address_id,user_id,batch_no,outgo,wid,wdr_id,postscript,best_time_start,best_time,sorting_id,wp_userid,order_id,order_sn as order_num,order_status as order_state,shipping_status,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
            ->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('add_time desc,order_id desc')->select();
        //dump(M('order_info')->getLastSql());
        if($list){
            $push_array = array();
            foreach ($list as $k=>$v){
                $one_order = $this->get_order_info($v);
                if($v['order_state']!=2 && $v['sorting_id']==0){
                    $one_order['order_state']=0; //待配货
                }elseif ($v['order_state']!=2 && $v['sorting_id']!=0&&$v['shipping_status']==3){
                    $one_order['order_state']=1;  //配货中
                }elseif($v['order_state']!=2 && $v['shipping_status']==5){
                    $one_order['order_state']=2;  //完成配货
                }elseif($v['order_state']!=2 && $v['shipping_status']==1){
                    $one_order['order_state']=4;  //发货中
                }elseif($v['order_state']!=2 && $v['shipping_status']==2){
                    $one_order['order_state']=5;  //已送达
                }else{
                    returnApiError('此订单为错误订单');
                }

                $re_goods_list = $this->re_goods_list($v['order_id'],$wid);
                if($re_goods_list){
                    $one_order['goods_list_back']=$re_goods_list;
                }
                $goods_list = $this->sh_goods_list($v['order_id'],$wid);
                if($goods_list){
                    $one_order['goods_list']=$goods_list;
                }
                $cold_data = $this->check_goods($goods_list);
                $one_order['is_cold'] = $cold_data['is_cold'];
                $one_order['is_ice'] = $cold_data['is_ice'];
                $one_order['is_nom'] = $cold_data['is_nom'];
                array_push($push_array,$one_order);
                unset($one_order);
            }
            returnApiSuccess(array('list'=>$push_array,'is_last'=>$is_last),'success');
        }else{
            returnApiError('数据为空');
        }

    }

    /**
     * 开始配货
     * rui poptser@foxmail.com 2016-10-11 11:32:22
     */
    // TODO 开始配货 deploy
    public function deploy(){
        //returnApiError("已暂停使用此功能，请使用新版拣货端");
        $order_id = I('post.order_id','intval');    //订单号
        $user_id = I('post.user_id','intval');

        $this->check_user($user_id);    //检查用户
        $wid = $this->get_user_wid_identity($user_id);

        $result = $this->deploy_order_action($user_id,$order_id,$wid);
        if($result){
            returnApiSuccess(null,"已开始配货");
        }else{
            returnApiError("配货失败:\n联系客服查找配货失败原因");
        }
    }

    /**
     * 配货完成
     * rui poptser@foxmail.com 2016-10-11 14:28:17
     */
    // TODO 配货完成 deployed
    public function deployed(){
        //returnApiError("已暂停使用此功能");
        $order_id = I('post.order_id','intval');    //订单号
        $user_id = I('post.user_id','intval');
        $this->check_user($user_id);    //检查用户
        $wid = $this->get_user_wid_identity($user_id);
        //$where = "196_admin_id = 0 AND order_id = ".$order_id." AND wid = ".$wid;
        $where = "k3cn_sn IS NULL AND order_id = ".$order_id." AND wid = ".$wid;
        $where = $where." AND sorting_id = ".$user_id." AND shipping_status = 3 AND order_status!=2 AND pay_status >= 2";

        $data['sorting_id'] = $user_id;
        $data['shipping_status'] = 5;   //修改为完成配货
        $data['sorting_time'] = gmtime();
        $result = M("order_info")->where($where)->save($data);    //修改订单信息表中的
        if($result){
            //修改成功，写入日志
            $order_info = M("order_info")->where("order_id = ".$order_id)->find();
            $a=array(
                'order_id'=>$order_id,
                'user_id'=>$user_id,
                'order_status'=>$order_info['order_status'],
                'shipping_status'=>5,
                'pay_status'=>$order_info['pay_status'],
                'to_user'=>1,
                'action_note'=>'配货完成'
            );


            A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
            A("Distribution")->record_logistics($order_id,5,"配货完成");
            returnApiSuccess(null,"已完成配货");
        }else{
            $order_info = M("order_info")->where("order_id = ".$order_id)->find();
            if($order_info['wid']!=$wid) returnApiError("非本仓库订单,此单属于仓库:".$order_info['wid'].":".$wid);
            if($order_info['sorting_id']!=$user_id) returnApiError("已被别人配货，配货人：".$order_info['sorting_id']);
            if($order_info['shipping_status']!=3) returnApiError("订单不在配货中状态{$order_info['shipping_status']}");
            if($order_info['order_status']==2) returnApiError("订单已被取消{$order_info['order_sn']}");
            if($order_info['pay_status']!=2 && $order_info['pay_status']!=3) returnApiError("订单还未支付{$order_info['order_sn']}");
            returnApiError("未知错误");
        }
    }


    /**
     * 获取订单商品详情
     * rui poptser@foxmail.com 2016-10-11 15:25:39
     */
    // TODO 获取订单商品详情 get_goods_handle_list
    public function get_goods_handle_list(){
        $order_id = I('post.order_id','intval');    //订单号
        $user_id = I('post.user_id','intval');

        $this->check_user($user_id);    //检查用户
        $wid = $this->get_user_wid_identity($user_id);


        if(!is_numeric($order_id)){
            returnApiError("订单ID错误");
        }


        $my_w_order = M("order_info")->where("order_id =".$order_id." AND wid = ".$wid)->getField('order_id');

        if($my_w_order){
            $rui_goods_list = array();
            $goods_list = $this->get_goods_list_real($my_w_order); //不包含赠品

            //dump($goods_list);

            foreach ($goods_list as $key=>$value){
                $goods_lists['count'] = $value['real_num'];
                $goods_lists['name'] = $value['goods_name'];
                $goods_lists['price'] = $value['goods_price'];
                $goods_lists['id'] = $value['goods_id'];
                $goods_lists['goods_id'] = $value['goods_id'];
                $goods_lists['rec_id'] = $value['rec_id'];
                $goods_lists['act_id'] = $value['act_id'];
                $goods_lists['selected'] = $value['selected'];
                $goods_lists['order_id'] = $order_id;
                $goods_lists['goods_number'] = $value['goods_sn'];
                $goods_lists['giving'] = $value['giving'];
                $goods_lists['store_count'] = M("goods_storage")->where("goods_id =".$value['goods_id']." AND wid = ".$wid)->getField('practical_num');

                array_push($rui_goods_list,$goods_lists);
            }
            $data['goods_list']=$rui_goods_list;
            $data['note']=$my_w_order['postscript'];;


//            $goods=M("order_goods")->field('selected,goods_id as id,goods_name as name,goods_price as price,goods_number as `count`')->where(array('order_id'=>$my_w_order))->select();
//
//            $data['goods_list']=$goods;
            returnApiSuccess($data,'已返回商品列表');
        }else{
            returnApiError("不存在此订单/非本仓库");
        }
    }


    /**
     * 新建配货群组并将订单修改为配货中
     * rui poptser@foxmail.com 2016-10-11 15:25:39
     */
    // TODO 新建配货群组 group_create
    public function group_create(){
        returnApiError("此功能暂停使用");
        $user_id = I('post.user_id','intval');
        $order_id_list = I('post.order_id_list');
        $name = I('post.name');
        $this->check_user($user_id);    //检查用户
        $wid = $this->get_user_wid_identity($user_id);

        $order_array = explode(",",$order_id_list);
        $order_array = array_filter($order_array);
        foreach ($order_array as $value){
            if(!is_numeric($value)&&!empty($value)){
                returnApiError("订单ID组错误");
                exit();
            }else{
                $r = M("order_info")->where("shipping_id =3 AND wid = ".$wid." AND order_id = ".$value." AND shipping_status in(0,3) AND sorting_id=0 AND order_status = 1 AND pay_status IN (2,3)")->count();
                if(!$r){
                    returnApiError("订单ID组中部分订单状态不正常");
                    exit();
                }
            }
        }

        $data['order_id'] = implode(",",$order_array);
        $data['group_name'] = $name;
        $data['user_id'] = $user_id;
        $data['wid'] = $wid;
        $data['addtime'] = time();
        $data['state'] = 0;

        $rs = M("sorting_order_group")->add($data);
        if($rs){
            $order_data['sorting_id']=$user_id;
            $order_data['shipping_status']=3;
            $where['order_id'] = array("in",$data['order_id']);
            $where['sorting_id'] = 0;
            $where['shipping_status'] = array("in","0,3");
            $new_order_list = M("order_info")->where($where)->getField("order_id",true);
            M("order_info")->where($where)->save($order_data);
            foreach ($new_order_list as $value){
                //写入日志
                $order_info = M("order_info")->where("order_id = ".$value)->find();
                $a=array(
                    'order_id'=>$value,
                    'user_id'=>$user_id,
                    'order_status'=>$order_info['order_status'],
                    'shipping_status'=>3,
                    'to_user'=>0,
                    'pay_status'=>$order_info['pay_status'],
                    'action_note'=>'备货中(群组操作)'
                );

                A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
                A("Distribution")->record_logistics($value,3,"开始配货");
            }

            returnApiSuccess(null,"新建群组成功");
        }
    }


    /**
     * 获取配货分组
     * rui poptser@foxmail.com 2016-10-11 17:32:48
     */
    // TODO 获取配货分组 group_list
    public function group_list(){
        $user_id=I('post.user_id','intval');

        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);

        $page=I('post.page','intval');



        $where['state']=0;
        $where['user_id']=$user_id;
        $where['wid']=$wid;


        $count=M('sorting_order_group')->where($where)->count();
//         $sql = M('order_info')->getLastSql();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('sorting_order_group')->field('id,group_name,order_id,state,addtime')->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('state asc,id desc')->select();
        if($list){
            foreach ($list as $k=>$v){

                $list[$k]['num_all'] = count(array_filter(array_unique(explode(",",$v['order_id']))));  //全部订单数
                $list[$k]['name'] = $v['group_name'];  //分组名称
                $list[$k]['time'] = date('Y-m-d H:i:s',$v['addtime']);  //时间

                $list[$k]['num_deploy'] = M("order_info")->where('shipping_status = 3 AND sorting_id !=0 AND order_id IN ('.$v['order_id'].')')->count();  //配货中
                $list[$k]['num_distribute'] = M("order_info")->where('shipping_status = 5 AND order_id IN ('.$v['order_id'].')')->count();  //配货完成

                $list[$k]['num_end'] = M("order_info")->where('shipping_status = 1 AND order_id IN ('.$v['order_id'].')')->count();  //已完成
                $list[$k]['end_state'] = $v['state'];  //时间





                $list[$k]['num_deploy']= M("order_info")->where("shipping_status = 3 AND order_id IN (".implode(',',array_filter(array_unique(explode(",",$v['order_id'])))).")")->count();//已配货数
            }
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }else{
            $list = array();
            $is_last =1;
            $count = 0;
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }
    }

    /**
     * 获取分组里面的订单列表
     * rui poptser@foxmail.com 2016-10-11 17:55:39
     */
    // TODO 获取分组订单列表 group_sub_list
    public function group_sub_list(){
        $user_id=I('post.user_id','');
        if(empty($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);
        $page=I('post.page','intval');
        $group_id=I('post.group_id','');
        if(empty($group_id)){
            returnApiError('参数错误');
        }
        $where['sorting_id']=$user_id;
        $where['pay_status']=array('gt',1);
        $where['order_status']=array('neq',2);
        $where['wid']=$wid;
        //$where['196_admin_id']=0;

        $group_order = M("sorting_order_group")->where("wid = ".$wid." AND id = ".$group_id." AND user_id = ".$user_id)->getField("order_id");


        //$group_order = array_filter(array_unique(explode(",",$group_order)));

        $where['order_id'] = array('in',$group_order);
        $count=M('order_info')->where($where)->count();
        //dump(M('order_info')->getlastsql());
        if($count==0){
            returnApiSuccess(array('list'=>array(),'is_last'=>1,'count_prepare'=>0),'无数据');
        }
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }

        $list=M('order_info')->field('distribution_company_id,shipping_id,address_id,user_id,batch_no,outgo,wid,wdr_id,postscript,best_time_start,best_time,shipping_status,sorting_id,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
            ->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('add_time desc,order_id desc')->select();

        if($list){
            $push_array = array();
            foreach ($list as $k=>$v){
                $one_order = $this->get_order_info($v);
                if($v['order_state']!=2 && $v['shipping_status']==0||$v['sorting_id']==0){
                    $one_order['order_state']=0; //待配货
                }elseif ($v['order_state']!=2 && $v['shipping_status']==3&&$v['sorting_id']!=0){
                    $one_order['order_state']=1;  //配货中
                }elseif($v['order_state']!=2 && $v['shipping_status']==5){
                    $one_order['order_state']=2;  //完成配货
                }elseif($v['order_state']!=2 && $v['shipping_status']==1){
                    $one_order['order_state']=4;  //发货中
                }elseif($v['order_state']!=2 && $v['shipping_status']==2){
                    $one_order['order_state']=5;  //已送达
                }else{
                    returnApiError('此订单为错误订单');
                }

                $re_goods_list = $this->re_goods_list($v['order_id'],$wid);
                if($re_goods_list){
                    $one_order['goods_list_back']=$re_goods_list;
                }
                $goods_list = $this->sh_goods_list($v['order_id'],$wid);
                if($goods_list){
                    $one_order['goods_list']=$goods_list;
                }
                array_push($push_array,$one_order);
                unset($one_order);
            }
            returnApiSuccess(array('list'=>$push_array,'is_last'=>$is_last),'success');
        }else{
            returnApiError('数据为空');
        }
    }


    /**
     * 群组配送完成
     * rui poptser@foxmail.com 2016-10-12 09:29:48
     */
    // TODO 群组配送完成 group_deployed
    public function group_deployed(){
        $user_id=I('post.user_id','intval');
        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);
        $group_id=I('post.group_id','');
        if(empty($group_id)){
            returnApiError('参数错误');
        }
        $group_order = M("sorting_order_group")->where("wid = ".$wid." AND id = ".$group_id." AND user_id = ".$user_id)->getField("order_id");
        $group_order = array_filter(array_unique(explode(",",$group_order)));
        $where['order_id'] = array('in',$group_order);
        $where['sorting_id']=$user_id;
        $where['pay_status']=array('gt',1);
        $where['order_status']=array('neq',2);
        $where['wid']=$wid;
        //$where['196_admin_id']=0;
        $where['shipping_status']=3;
        $order_data['shipping_status']=5;
        $new_order_list = M("order_info")->where($where)->getField("order_id",true);
        M("order_info")->where($where)->save($order_data);

        foreach ($new_order_list as $value){
            //写入日志
            $a=array(
                'order_id'=>$value,
                'user_id'=>$user_id,
                'order_status'=>1,
                'shipping_status'=>5,
                'pay_status'=>2,
                'to_user'=>0,
                'action_note'=>'备货完成(群组操作)'
            );
            A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
            A("Distribution")->record_logistics($value,5,"配货完成");
        }
        M("sorting_order_group")->where("id =".$group_id)->setField("state",1);

        returnApiSuccess(null,"群组配货完成");

    }
    private function findNum($str=''){
        $str=trim($str);
        if(empty($str)){return '';}
        $result='';
        for($i=0;$i<strlen($str);$i++){
            if(is_numeric($str[$i])){
                $result.=$str[$i];
            }
        }
        return $result;
    }
    public function newGetS($order_bag_name){
        $order_bag_info = $this->redis->get("laravel_cache:".$order_bag_name);

        $bag_info = unserialize($order_bag_info);
        if(empty($bag_info)){
            return $order_bag_info;
        }else{
            return unserialize($order_bag_info); // 获取缓存
        }

    }
    public function newSetS($order_bag_name,$vaule){
        $this->redis->set("laravel_cache:".$order_bag_name, serialize($vaule), 2592000);
        //$cache->$order_bag_name = $vaule; // 获取缓存
    }
    /**
     * 扫描二维码获取订单
     * rui poptser@foxmail.com 2016-10-10 17:11:20
     */
    // TODO 扫描二维码获取订单 scanner
    public function scanner(){
        $wp_userid=I('post.user_id','intval');
        $order_id=I('post.barcode');    //扫描得到的订单ID
        $order_number=I('post.order_number');   //手动输入的订单号后8位
        $is_zt=I('post.is_zt');   //判断是否为自提单
        $check_goods_out=I('post.check_goods_out');   //是否可以出仓
        $check_goods_back=I('post.check_goods_back');   //是否可以回仓
        $company_array = M("distribution_company_user")->where(array("user_id"=>$wp_userid))->getField("company_id",true);

        $wid = $this->get_user_wid_identity($wp_userid);
        if(!empty($company_array)){
            $where_zt['distribution_company_id'] = array("in",$company_array);
            $where['distribution_company_id'] = array("in",$company_array);
        }

        $where['wid'] = $wid;
        $where_zt['wid'] = $wid;
        //$where_zt['k3cn_sn'] = array("EXP","IS NULL");
        //$where['k3cn_sn'] = array("EXP","IS NULL");
        //$where['196_admin_id'] = 0;
        //$where_zt['196_admin_id'] = 0;

        $bag_info = 0;

        if(!empty($order_id)){
            $order_id = $this->findNum($order_id);
        }

        if(!empty($check_goods_out)||!empty($check_goods_back)){

            if($wp_userid==103){
                //returnApiError($order_id);
            }

            //检查是否可以出仓
            if(!empty($order_id)){
                if(strlen($order_id) > 9){
                    //扫出订单ID大于9，按订单编号查询
                    if(strlen($order_id) > 19){
                        //扫出订单ID大于19，按订单编号加分袋信息查询
                        $bag_info = substr($order_id, -5);
                        $where_zt['order_sn'] = substr($order_id, 0, 19);
                    }else{
                        if(strlen($order_id) == 13){
                            $bag_info = substr($order_id, -5);
                            $order_number = substr($order_id, 0, 8);
                            $where_zt['order_sn']=array("like","%".$order_number);
                        }else{
                            $where_zt['order_sn'] = $order_id;
                        }
                    }
                }else{
                    $where_zt['order_id'] = $order_id;
                }
            }elseif(!empty($order_number)){
                $where_zt['order_sn']=array("like","%".$order_number);
            }else{
                returnApiError("订单ID/订单号后8位为空");
            }


//            $where_zt['pay_status'] = array("in","2,3");
//            $where_zt['order_status']=array('neq',2);
//            $where_zt['shipping_id']=2; //到店自提订单
//            $where_zt['shipping_status']=2; //确认收货
            $zt_order = M("order_info")->
            field("k3cn_sn,quality_id as isCheck,quality_id,outgo,order_id,order_sn,pay_status,order_status,shipping_id,shipping_status,freeze_status")->
            where($where_zt)->find();
            if(empty($zt_order)){
                returnApiError("未找到此订单");
            }
            //returnApiSuccess($zt_order);
            if($zt_order['freeze_status']!=0&&$zt_order['shipping_status']!=2){
                returnApiError("此订单已提交问题单");
            }

            if($zt_order['order_status']!=2&&$zt_order['shipping_id']==3&&$zt_order['shipping_status']==5&&$zt_order['outgo']==0){
                if($zt_order['pay_status']==2||$zt_order['pay_status']==3){
                    $data['is_goods_out']= 1;   //可以出仓
                }else{
                    $data['is_goods_out']= 0;
                }
            }else{
                $data['is_goods_out']= 0;       //无法出仓
            }

            if($zt_order['outgo']==2){
                $data['is_goods_back']= 1;
            }else{
                $data['is_goods_back']= 0;
            }
            if($zt_order['order_status']!=2&&$zt_order['shipping_id']==2){
                if($zt_order['pay_status']==2||$zt_order['pay_status']==3){
                    $data['is_zt']= 1;
                }else{
                    $data['is_zt']= 0;
                }
            }else{
                $data['is_zt']= 0;              //不是自提单
                if(empty($zt_order['quality_id'])){
                    returnApiError("此订单还未质检:".$zt_order['quality_id']);
                }
            }

            if(!empty($data['is_zt'])){
                //判断是否可以自提
                if(!empty($order_id)){
                    if(strlen($order_id) > 9){
                        //扫出订单ID大于9，按订单编号查询
                        if(strlen($order_id) > 19){
                            //扫出订单ID大于19，按订单编号加分袋信息查询
                            $where_zt['order_sn'] = substr($order_id, 0, 19);
                        }else{
                            if(strlen($order_id) == 13){
                                $order_number = substr($order_id, 0, 8);
                                $where_zt['order_sn']=array("like","%".$order_number);
                            }else{
                                $where_zt['order_sn'] = $order_id;
                            }
                        }
                    }else{
                        $where_zt['order_id'] = $order_id;
                    }
                }elseif(!empty($order_number)){
                    $where_zt['order_sn']=array("like","%".$order_number);
                }else{
                    returnApiError("订单ID/订单号后8位为空");
                }


                $where_zt['pay_status'] = array("in","2,3");
                $where_zt['order_status']=array('neq',2);
                $where_zt['shipping_id']=2; //到店自提订单
                $where_zt['shipping_status']=2; //确认收货
                $zt_order = M("order_info")->field("order_id,order_sn,k3cn_sn")->where($where_zt)->find();
                if ($zt_order){
                    $zt_order['is_zt'] =1;
                    returnApiSuccess($zt_order,"此单为自提单");
                }
            }





            $data['order_id'] = $zt_order['order_id'];
            if ($zt_order){
                if(!empty($check_goods_out)){
                    if($data['is_goods_out']==1){
                        if(empty($zt_order['k3cn_sn'])){
                            $order_bag_info = S("order_bag_".$zt_order['order_id']);
                        }else{
                            $order_bag_info = $this->newGetS("order_bag_".$zt_order['order_id']);
                        }
                        if(empty($order_bag_info)){
                            returnApiError('未找到分袋信息');
                        }
                        if(!empty($order_bag_info)&&strlen($bag_info)!=5){
//                            foreach ($order_bag_info as $key=>$value){
//                                $order_bag_info[$key]['is_scan'] = 1;
//                            }
//                            if(empty($zt_order['k3cn_sn'])){
//                                S("order_bag_".$zt_order['order_id'],$order_bag_info);
//                            }else{
//                                $this->newSetS("order_bag_".$zt_order['order_id'],$order_bag_info);
//                            }
//                            $str = ",文佳扫描，强行全部标记已扫描";
                            returnApiError("此订单有分袋信息，请扫描正确的条码");
                        }

                        if($bag_info&&strlen($bag_info)>4){
                            //分袋信息处理

                            $str = ",本次扫描袋号：".substr($bag_info, 2, 2);
                            if($order_bag_info){
                                foreach ($order_bag_info as $key=>$value_s){
                                    if($value_s['current']==substr($bag_info, 2, 2)){
                                        $order_bag_info[$key]['is_scan'] = 1;
                                    }
                                }
                            }
                            //dump($order_bag_info);
                            if(empty($zt_order['k3cn_sn'])){
                                S("order_bag_".$zt_order['order_id'],$order_bag_info,86400);
                            }else{
                                $this->newSetS("order_bag_".$zt_order['order_id'],$order_bag_info);
                            }

                            $is_scan_num = 0;
                            foreach ($order_bag_info as $key=>$value_s){
                                if($value_s['is_scan']==1){
                                    $is_scan_num++;
                                }
                            }

                            if($order_bag_info[0]['all']==$is_scan_num){
                                $tips_msg = "此单分袋已全部确认";
                                //可以出仓，生成一个序列  配送序号
                                if(S('baidu_order_sequence'.date("d"))){
                                    $baidu_order_sequence = S('baidu_order_sequence'.date("d"));
                                    if($baidu_order_sequence[$zt_order['order_id']]){
                                        $data['baidu_order_sequence'] = $baidu_order_sequence[$zt_order['order_id']];
                                    }else{
                                        $max = max($baidu_order_sequence);
                                    }
                                }else{
                                    $baidu_order_sequence = array();
                                    $max = 0;
                                }
                                if(!$data['baidu_order_sequence']){
                                    $baidu_order_sequence[$zt_order['order_id']] = $max+1;
                                    S('baidu_order_sequence'.date("d"),$baidu_order_sequence,86400);
                                    $data['baidu_order_sequence'] = $max+1;
                                }
                            }else{
                                $tips_msg = "共：".$order_bag_info[0]['all']." 未确认：".($order_bag_info[0]['all']-$is_scan_num);
                            }
                        }else{
                            //可以出仓，生成一个序列  配送序号
                            if(S('baidu_order_sequence'.date("d"))){
                                $baidu_order_sequence = S('baidu_order_sequence'.date("d"));
                                if($baidu_order_sequence[$zt_order['order_id']]){
                                    $data['baidu_order_sequence'] = $baidu_order_sequence[$zt_order['order_id']];
                                }else{
                                    $max = max($baidu_order_sequence);
                                }
                            }else{
                                $baidu_order_sequence = array();
                                $max = 0;
                            }
                            if(!$data['baidu_order_sequence']){
                                $baidu_order_sequence[$zt_order['order_id']] = $max+1;
                                S('baidu_order_sequence'.date("d"),$baidu_order_sequence,86400);
                                $data['baidu_order_sequence'] = $max+1;
                            }
                            $tips_msg = "未找到分袋信息";
                        }


                        $a=array(
                            'order_id'=>$zt_order['order_id'],
                            'user_id'=>I('post.user_id'),
                            'order_status'=>$zt_order['order_status'],
                            'shipping_status'=>$zt_order['shipping_status'],
                            'pay_status'=>$zt_order['pay_status'],
                            'to_user'=>0,
                            'action_note'=>'扫描出仓：'.$tips_msg.$str,
                        );
                        A("Distribution")->record_diliveryman_log($a);



                        returnApiSuccess($data,null,$tips_msg);
                    }else{
                        //returnApiSuccess($data);
                        returnApiError('此单无法出仓');
                    }
                }
                if(!empty($check_goods_back)){
                    if($data['is_goods_back']){
                        returnApiSuccess($data);
                    }else{
                        returnApiError("此单无法回仓");
                    }
                }

            }else{
                returnApiError('无此订单');
            }


        }

        if(empty($order_id)){
            if(!isset($wp_userid) || !isset($order_number)){
                if(!is_numeric($order_number)){
                    returnApiError('参数错误');
                }
            }
        }else{
            if(!isset($wp_userid) || !isset($order_id)){
                returnApiError('参数错误');
            }
        }


        $this->check_user($wp_userid);

        //$where['wp_userid']=$wp_userid;
        if(!empty($order_id)){
            if(strlen($order_id) > 9){
                //扫出订单ID大于9，按订单编号查询
                if(strlen($order_id) > 19){
                    $where['order_sn'] = substr($order_id, 0, 19);
                }else{
                    $where['order_sn'] = $order_id;
                }
            }else{
                $where['order_id'] = $order_id;
            }
        }elseif(!empty($order_number)){
            $where['order_sn']=array("like","%".$order_number);
        }


        $where['pay_status']=array('gt',1);
        $where['order_status']=array('neq',2);
        //$where['shipping_id']=3;
        $where['outgo']=0;
        $where['_string'] = "(is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1))";
        $order=M('order_info')->field('freeze_status,distribution_company_id,shipping_id,quality_id,address_id,user_id,batch_no,outgo,wid,wdr_id,postscript,best_time_start,best_time,sorting_id,wp_userid,order_id,order_sn as order_num,order_status as order_state,shipping_status,add_time as order_time,consignee as name,mobile as phone,sign_building,country,province,city,district,address,sorting_id,address_name')->where($where)->find();
        if($order['freeze_status']!=0&&$order['shipping_status']!=2){
            returnApiError("此订单已提交问题单");
        }
        //dump(M('order_info')->getLastSql());
        if($order){
            try {
                $data = $this->get_order_info($order);

                if($order['quality_id']>0){
                    $data['isCheck'] = 1;
                }else{
                    $data['isCheck'] = 0;
                }
                //dump($data);
                if ($order['sorting_id'] == 0) {
                    $data['order_state'] = 0; //待配货
                } elseif ($order['sorting_id'] != 0&&($order['shipping_status']==3 ||$order['shipping_status']==0)) {
                    $data['order_state'] = 1;  //配货中
                } elseif ($order['shipping_status'] == 5) {
                    $data['order_state'] = 2;  //完成配货
                } elseif ($order['shipping_status'] == 1) {
                    $data['order_state'] = 4;  //发货中
                } elseif ($order['shipping_status'] == 2) {
                    $data['order_state'] = 5;  //已送达
                }

                $goods_list = $this->sh_goods_list($order['order_id'],$wid);
                if($goods_list){
                    $data['goods_list']=$goods_list;
                }
                $re_goods_list = $this->re_goods_list($order['order_id'],$wid);
                if($re_goods_list){
                    $data['goods_list_back']=$re_goods_list;
                }
                $cold_data = $this->check_goods($goods_list);
                $data['is_cold'] = $cold_data['is_cold'];
                $data['is_ice'] = $cold_data['is_ice'];
                $data['is_nom'] = $cold_data['is_nom'];
                returnApiSuccess(array('distribute'=>$data));
            }catch (Exception $e){
                returnApiErrorExample($e->getMessage());
            }
        }else{
            unset($where['k3cn_sn']);
            $k3cn_sn = M("order_info")->where($where)->getField("k3cn_sn");
            if(empty($k3cn_sn)){
                returnApiError('查无此条码/非本仓库订单/订单不可配货/预售单/非本区域单');
            }else{
                returnApiError('金蝶订单，请使用新版本处理');
            }

        }
    }


    /**
     * 获取配送公司订单数
     */
    public function get_distribution_company(){
        $wp_userid=I('post.user_id','intval');
        if(!isset($wp_userid)){
            returnApiError('参数错误');
        }
        $wid = $this->get_user_wid_identity($wp_userid);
        $year     =I('post.year','intval');     //年份
        $month    =I('post.month','intval');    //月份
        $day      =I('post.day','intval');      //日期
        //$this->check_user($wp_userid);
        //$wid = $this->get_user_wid_identity($wp_userid);
        $company_array_id = M("distribution_company_user")->where(array("user_id"=>$wp_userid))->getField("company_id",true);
        if(!empty($company_array)){
            $where_dis['distribution_company_id'] = array("in",$company_array_id);
            $company_array = M("distribution_company")->field("id,company_name,lite_name")->where($where_dis)->select();
        }else{
            $company_array = M("distribution_company")->field("id,company_name,lite_name")->select();
        }
        $new_array = array(
            "id"=>0,
            "lite_name"=>"食得鲜",
            "company_name"=>"广州食得鲜网络科技有限公司"
        );
        $company_array[] = $new_array;
        //array_push($company_array,$new_array)
        $where_tow['shipping_status']= array('in','0,3');	//未备货中
        $where_tow['sorting_id']=0;	//未备货中
        $where_tow['outgo']=0;	    //商品未出仓
        $where_tow['wid']=$wid;
        $where_tow['pay_status']=array('in','2,3');
        $where_tow['order_status']= array('neq',2);
        $where_tow['shipping_id']=3;        //送货上门订单
        $where_tow['k3cn_sn']=array("EXP","IS NULL");       //
        $order_info = M("order_info");
        foreach ($company_array as $key=>$value){
            $where_tow['distribution_company_id']=$value['id'];        //送货上门订单
            $where_tow['_string'] = "TO_DAYS('".$year."-".$month."-".$day."') =  TO_DAYS(from_unixtime(best_time))
            AND (is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1))";

            $order_array = $order_info->where($where_tow)->getField("order_id",true);
            $order_num = count($order_array);

            //$company_array[$key]['order_number_sql'] = $order_info->getLastSql();  //今日订单
            $company_array[$key]['order_number'] = $order_num;  //今日订单

            $where_tow['_string'] = "TO_DAYS('".$year."-".$month."-".$day."') >  TO_DAYS(from_unixtime(best_time))
            AND (is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1))"; //之前订单

            $other_array = $order_info->where($where_tow)->getField("order_id",true);

            $company_array[$key]['other_number'] = count($other_array);

            if($order_num>0&&count($other_array)>0){
                $un_order_list = array_merge($other_array,$order_array);
            }else{
                if($order_num>0){
                    $un_order_list = $order_array;
                }
                if(count($other_array)>0){
                    $un_order_list = $other_array;
                }
            }
            if(count($un_order_list)>0){
                $order_free_single = M("order_info_free_single")->
                where(array("order_id"=>array("in",$un_order_list)))->count();
            }else{
                $order_free_single = 0;
            }


            $company_array[$key]['free_single'] = $order_free_single;
        }
        returnApiSuccess(array("data"=>$company_array));
    }
    /**
     * 获取订单筛选条件
     */
    public function get_order_condition(){
        returnApiError("客户端版本过旧，请更新后使用");
    }
    /**
     * 获取送货区域订单数
     */
    public function get_order_condition_area(){
        returnApiError("客户端版本过旧，请更新后使用");
    }


    /**
     * 获取订单筛选条件
     * rui poptser@foxmail.com 2016-10-21 15:04:25
     */
    // TODO 获取订单筛选条件 get_order_condition
    public function get_order_condition_new(){
        $wp_userid=I('post.user_id','intval');
        $distribution_company_id  =I('post.distribution_company_id','intval');  //配送公司ID
        if(!isset($wp_userid)||!isset($distribution_company_id)){
            returnApiError('参数错误');
        }
        //$this->check_user($wp_userid);
        $wid = $this->get_user_wid_identity($wp_userid);

        $year     =I('post.year','intval');     //年份
        $month    =I('post.month','intval');    //月份
        $day      =I('post.day','intval');      //日期

        $is_ps=I('post.is_ps');
        if(empty($is_ps)){
            //配货
            $where_tow['shipping_status']= array('in','0,3');	//未备货中
            $where_tow['sorting_id']=0;	//未备货中
            $where_tow['wid']=$wid;
            $where_tow['outgo']=0;	    //商品未出仓
        }else{
            //配送
            $where_tow['shipping_status']= 5;	//已配货完成
            $where_tow['wp_userid']=0;	//无配送员接单
            $where_tow['outgo']=1;	    //商品已经出仓
            $where_tow['station']=1;	    //商品已经到站
        }

        $where_tow['pay_status']=array('in','2,3');
        $where_tow['order_status']= array('neq',2);
        $where_tow['distribution_company_id']= $distribution_company_id;
        $where_tow['shipping_id']=3;        //送货上门订单
        $where_tow['k3cn_sn']=array("EXP","IS NULL");
        //$where_tow['196_admin_id']=0;        //

        //剔除预售订单
        $where_list = "(is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1)) AND ";

        $order_info = M('order_info');


        $new_array = $order_info->where("TO_DAYS('".$year."-".$month."-".$day."') =  TO_DAYS(from_unixtime(best_time))")
            ->where($where_tow)->field("best_time_start,best_time")->group("best_time_start,best_time")->select();

        foreach ($new_array as $key=>$value){
            //$time_array = explode("|",$value);
            $where_1 = $where_list."best_time_start='".$value['best_time_start']."'  AND best_time='".$value['best_time']."'";
            $un_order_list = $order_info->where($where_1)->where($where_tow)->getField("order_id",true);

            $str_num = count($un_order_list);

            if($str_num>0){

                $order_free_single = M("order_info_free_single")->
                where(array("order_id"=>array("in",$un_order_list)))->count();

                $str_1 = " ( ".$str_num." )";
                $data['list_time'][] = array(
                    "id" =>date("H:i",$value['best_time_start'])."|".date("H:i",$value['best_time']),
                    "free_single"=>$order_free_single,
                    "value" =>date("H:i",$value['best_time_start'])." - ".date("H:i",$value['best_time'])." ".$str_1
                );
            }

        }

        $where_9 = $where_list."TO_DAYS('".$year."-".$month."-".$day." 10:00:00"."') >  TO_DAYS(from_unixtime(best_time))";

        $un_order_list = $order_info->where($where_9)->where($where_tow)->getField("order_id",true);
        $str_num = count($un_order_list);


        if($str_num>0){
            $str_9 = " ( ".$str_num." )";
            $order_free_single = M("order_info_free_single")->
            where(array("order_id"=>array("in",$un_order_list)))->count();
        }else{
            $str_9 = "";
            $order_free_single = 0;
        }
        $data['list_time'][] = array(
            "id" =>99999,
            "free_single"=>$order_free_single,
            //"sql" =>$order_info->getLastSql(),
            "value" =>"超时订单 ".$str_9
        );

        //全部单

        unset($where_tow['distribution_company_id']);
        $today_order_num = $order_info->where($where_tow)->where($where_list."TO_DAYS(from_unixtime(best_time)) = TO_DAYS('".$year."-".$month."-".$day." 10:00:00')")->count();
        $other_order_num = $order_info->where($where_tow)->where($where_list."TO_DAYS(from_unixtime(best_time)) < TO_DAYS('".$year."-".$month."-".$day." 10:00:00')")->count();
        $data['count_prepare'] = $today_order_num."+".$other_order_num;

        returnApiSuccess($data,"已返回数据");
    }


    /**
     * 获取送货区域订单数
     * TODO 根据时间，送货区域获取订单(仅订单数) get_order_condition_area
     */
    public function get_order_condition_area_new(){
        $wp_userid=I('post.user_id','intval');  //用户ID
        $year     =I('post.year','intval');     //年份
        $month    =I('post.month','intval');    //月份
        $day      =I('post.day','intval');      //日期
        $time_id  =I('post.time_id','intval');  //配送时间段ID
        $distribution_company_id  =I('post.distribution_company_id','intval');  //配送公司ID
        if(empty($wp_userid)||empty($year)||empty($month)||empty($day)||!isset($distribution_company_id)){
            returnApiError('参数错误');
        }
        //$this->check_user($wp_userid);

        $wid = $this->get_user_wid_identity($wp_userid);
        //dump($wid);
        $other =  false;

        $where_tow['pay_status']=array('in','2,3');
        $where_tow['order_status']= array('neq',2);
        $where_tow['distribution_company_id']= $distribution_company_id;
        $where_tow['shipping_id']=3;        //送货上门订单
        $where_tow['k3cn_sn']=array("EXP","IS NULL");
        //$where_tow['196_admin_id']=0;        //


        if($time_id==99999){
            $other =  true;
        }else{
            $time_array =  explode("|",$time_id);
            $start_time = $time_array[0].":00";
            $end_time = $time_array[1].":00";
        }
        try{
            $best_time_str = $year."-".$month."-".$day." 12:00:00";
            if($other){
                $where['_string'] = "(`is_presell` = 0 OR (`is_presell` = 1 AND `buckle_inventory` = 1)) AND TO_DAYS('".$best_time_str."') > TO_DAYS(from_unixtime(`best_time`))";
            }else{
                $where['_string'] = "(`is_presell` = 0 OR (`is_presell` = 1 AND `buckle_inventory` = 1))";
                $where['best_time_start']=$best_time_start = strtotime($year."-".$month."-".$day." ".$start_time);
                $where['best_time']=$best_time = strtotime($year."-".$month."-".$day." ".$end_time);
            }
        }catch (Exception $s){
            returnApiError("时间点错误");
        }



        //配送区域
        $data['list_area'] = array();
        $is_ps=I('post.is_ps');

        if(empty($is_ps)){
            //配货端
            //按具体订单方式筛选订单
            $where_tow['wid']=$wid;
            $where_tow['shipping_status']= array('in','0,3');	//未备货中
            $where_tow['sorting_id']=0;	//未备货中
            $where_tow['outgo']=0;	    //商品未出仓


            $new_data = M('order_info')->where($where)->where($where_tow)->getField('wdr_id',true);


            //$data['sql2'] = $default_order;
            foreach ($new_data as $key=>$value){
                //id  name  count
                $j=true;
                foreach ($data['list_area'] as $key2=>$value2){
                    if($value ==$value2['id']){
                        $j=false;
                    }
                }
                if($j){
                    $my_data['id'] = $value;
                    if($value==0){
                        $my_data['name'] ="未定义区域";
                        $my_data['free_single'] = 0;
                    }else{
                        $my_data['name'] = M("warehouse_deliver_region")->where(array("id"=>$value))->getField("name");
                        $un_order_list = M('order_info')->where($where)->
                        where($where_tow)->where("wdr_id=".$value)->getField("order_id",true);
                        $order_free_single = M("order_info_free_single")->
                        where(array("order_id"=>array("in",$un_order_list)))->count();
                        $my_data['free_single'] = $order_free_single;
                    }
                    $count_array = array_count_values($new_data);
                    $my_data['count'] = $count_array[$value];
                    array_push($data['list_area'],$my_data);
                }
            }

            $data['count_prepare'] = 0;

        }else{
            //配送端
            //按具体订单方式筛选订单
            if(!empty($company_array)){
                $where_tow['distribution_company_id'] = array("in",$company_array);
            }
            $where_tow['shipping_status']= 5;	//配货完成
            $where_tow['wp_userid']=0;	//配送员ID 为空
            $where_tow['outgo']=1;	    //商品已经出仓
            $where_tow['station']=1;	    //商品已经到站

            $new_data = M('order_info')->where($where)->where($where_tow)->getField('wdr_id',true);


            //$data['sql2'] = $default_order;
            foreach ($new_data as $key=>$value){
                //id  name  count
                $j=true;
                foreach ($data['list_area'] as $key2=>$value2){
                    if($value ==$value2['id']){
                        $j=false;
                    }
                }
                if($j){
                    $my_data['id'] = $value;
                    if($value==0){
                        $my_data['name'] ="未定义区域";
                        $my_data['free_single'] = 0;
                    }else{
                        $my_data['name'] = M("warehouse_deliver_region")->where(array("id"=>$value))->getField("name");
                        $un_order_list = M('order_info')->where($where)->
                        where($where_tow)->where("wdr_id=".$value)->getField("order_id",true);
                        $order_free_single = M("order_info_free_single")->
                        where(array("order_id"=>array("in",$un_order_list)))->count();
                        $my_data['free_single'] = $order_free_single;
                    }
                    $count_array = array_count_values($new_data);
                    $my_data['count'] = $count_array[$value];

                    array_push($data['list_area'],$my_data);
                }
            }

            $data['count_prepare'] = 0;
        }


        returnApiSuccess($data,"已返回数据");
    }

    /**
     * 随机获取一条当前仓库的订单
     * rui poptser@foxmail.com 2016-10-20 13:58:38
     */
    public function get_order(){
        returnApiError("客户端版本过旧，请更新后使用");
    }
    /**
     * 随机获取一条当前仓库的订单
     * rui poptser@foxmail.com 2017-08-20 13:58:38
     */
    // TODO 随机获取一条当前仓库的订单 get_order
    public function get_order_new(){
        $wp_userid=I('post.user_id','intval');  //用户ID
        $year     =I('post.year','intval');     //年份
        $month    =I('post.month','intval');    //月份
        $day      =I('post.day','intval');      //日期
        $time_id  =I('post.time_id','intval');  //配送时间段ID
        $area_id  =I('post.area_id','intval');  //配送区域ID
        $distribution_company_id  =I('post.distribution_company_id','intval');  //配送公司ID
        if(empty($wp_userid)||empty($year)||empty($month)||empty($day)){
            returnApiError('参数错误');
        }
        //$this->check_user($wp_userid);
        $wid = $this->get_user_wid_identity($wp_userid);

        if(isset($area_id)){
            $where['wdr_id'] = $area_id;
        }
        $where['k3cn_sn']=array("EXP","IS NULL");
        $where['distribution_company_id'] = $distribution_company_id;
        //$where['196_admin_id'] = 0;

        $where['_string'] = "(is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1))";    //现售条件
        $other =  false;



        if($time_id==99999){
            $other =  true;
        }else{
            $time_array =  explode("|",$time_id);
            $start_time = $time_array[0].":00";
            $end_time = $time_array[1].":00";
        }
        try{
            $best_time_str = $year."-".$month."-".$day." 12:00:00";
            if($other){
                $where['_string'] = "(is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1)) AND TO_DAYS('".$best_time_str."') >  TO_DAYS(from_unixtime(best_time))";
            }else{
                $where['best_time_start']=$best_time_start = strtotime($year."-".$month."-".$day." ".$start_time);
                $where['best_time']=$best_time = strtotime($year."-".$month."-".$day." ".$end_time);
            }
        }catch (Exception $s){
            returnApiError("时间点错误");
        }

        //查询是否有未完成的 随机获取单

        $is_ps=I('post.is_ps');

        if(empty($is_ps)) {

            //todo 随机获取订单 配货
            $where['sorting_id'] = 0;
            $where['shipping_status'] = array("in","0,3");
            $where['order_status'] = array("neq",2);
            $where['pay_status'] = array("in","2,3");
            $where['shipping_id']=3;
            $where['wid'] = $wid;
            $where['outgo']=0;	    //商品未出仓

            $where_random['sorting_id'] = $wp_userid;
            $where_random['is_random'] = 1;
            $where_random['shipping_status'] = array("in","0,3");
            $where_random['order_status'] = array("neq",2);
            $where_random['pay_status'] = array("in","2,3");
            $where_random['shipping_id']=3;

            $random_num = M("order_info")->field('batch_no,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                ->where($where_random)->count();
            if($random_num>49){
                returnApiError("ヾ(≧O≦)〃嗷~\n已达50个订单\n请先完成配货");
            }


            $result = M("order_info")->field('distribution_company_id,shipping_id,address_id,user_id,batch_no,sorting_id,wdr_id,wid,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                ->order('rand()')->where($where)->find();
            //dump(M("order_info")->getLastSql());

            if($result){

                $action_status = $this->deploy_order_action($wp_userid,$result['order_id'],$wid,true);

                if(!$action_status){
                    returnApiError("开始配货失败");
                }

                $result = $this->get_order_info($result);   //订单相关信息

                $old_data = M("order_info")->where('order_id = '.$result['order_id'])->find();
                if ($old_data['sorting_id'] == 0) {
                    $data['order_state'] = 0; //待配货
                } elseif ($old_data['sorting_id'] != 0&&($old_data['shipping_status']==3 ||$old_data['shipping_status']==0)) {
                    $data['order_state'] = 1;  //配货中
                } elseif ($old_data['shipping_status'] == 5) {
                    $data['order_state'] = 2;  //完成配货
                } elseif ($old_data['shipping_status'] == 1) {
                    $data['order_state'] = 4;  //发货中
                } elseif ($old_data['shipping_status'] == 2) {
                    $data['order_state'] = 5;  //已送达
                }
                $goods_list = $this->sh_goods_list($result['order_id'],$wid);
                if($goods_list){
                    $result['goods_list']=$goods_list;  //商品当前列表
                }
                $re_goods_list = $this->re_goods_list($result['order_id'],$wid);
                if($re_goods_list){
                    $result['goods_list_back']=$re_goods_list;  //退款列表
                }
                $default_order = M("activity_quota")->where("order_id=" . $result['order_id'])->count();
                if ($default_order > 0) {
                    $result['default_order'] = 0;
                } else {
                    $result['default_order'] = 1;
                }
                $data['deploy'] = $result;
                returnApiSuccess($data,'已返回配货单');
            }else{
                returnApiError('数据为空');
            }
        }else {
            //TODO 随机获取订单  配送
            //dump('配送');
            $weight = I("post.weight");     //获取商品重量（单位KG）

            $where['wp_userid'] = 0;
            $where['shipping_status'] = 5;
            $where['order_status'] = array("neq", 2);
            $where['pay_status'] = array("in", "2,3");
            $where['shipping_id'] = 3;
            $where['outgo']=1;	    //商品已经出仓


            $where_random['wp_userid'] = $wp_userid;
            $where_random['is_random_ps'] = 1;
            $where_random['shipping_status'] = 5;
            $where_random['order_status'] = array("neq", 2);
            $where_random['pay_status'] = array("in", "2,3");
            $where_random['shipping_id'] = 3;
            $where_random['outgo']=1;	    //商品已经出仓

            $random_num = M("order_info")->field('batch_no,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                ->where($where_random)->count();
            if ($random_num > 49) {
                returnApiError("ヾ(≧O≦)〃嗷~\n已达50个订单\n请先完成配送");
            }

            $result = M("order_info")->field('address_id,user_id,batch_no,sorting_id,wdr_id,wid,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                ->order('rand()')->where($where)->find();

            //dump($result);
            if ($result) {
                A('Distribution')->distribute($result['order_id'],true);
            } else {
                returnApiError('数据为空');
            }

        }

    }

    /**
     * 订单打印
     * rui poptser@foxmail.com 2016-10-21 14:43:29
     */
    // TODO 订单打印 order_print
    public function order_print(){
        $wp_userid=I('post.user_id','intval');  //用户ID
        $order_id     =I('post.order_id','intval');     //订单ID
        if(empty($wp_userid)||empty($order_id)){
            returnApiError('参数错误');
        }
        $this->check_user($wp_userid);


        $Model=new Model();
        // 订单详情
        $total_fee = " (a.goods_amount - a.discount + a.tax + a.shipping_fee + a.insure_fee + a.pay_fee + a.pack_fee + a.card_fee) AS total_fee ";
        $sql = "SELECT a.*,b.zoning_id,b.name AS 'region_name'," . $total_fee . " FROM sdx_order_info AS a  LEFT JOIN sdx_warehouse_deliver_region AS b ON b.id=a.wdr_id WHERE a.order_id=" . $order_id;
        $order = $Model->query($sql);

        $order= $order[0];
        if(!empty($order['distribution_company_id'])){
            $company_name = M("distribution_company")->where(array("id"=>$order['distribution_company_id']))->getField("lite_name");
        }
        if(empty($company_name)){
            $company_name = "自配送";
        }
        $data['company_name'] =$company_name."-".$order['distribution_company_area'];
        $data['area_name'] = $company_name."-".$order['distribution_company_area']."\n".M("zoning_cate")->where(array("id"=>$order['zoning_id']))->getField("name")."-".$order['region_name'];
        /* 格式化订单字段 */
        if (!empty($order)) {
        }else{
            returnApiError("未查询到此单");
        }
        //配送地址处理
        $order['address'] = $order['address'] . $order['sign_building'] . $order['address_name'];

        //期望时间处理
        if (!empty($order['best_time'])) {
            if ($order['best_time_start'] > 0) {
                $best_time_start = date('Y-m-d H:i', $order['best_time_start']);
            } else {
                $best_time_start = date('Y-m-d H:i', $order['best_time'] - 7199);
            }
            $order['best_time'] = $best_time_start . "  -   " . date('H:i', $order['best_time'] + 1);
        }
        //计算优惠金额

        $goods_list = $this->get_goods_list_real($order_id);
        $data['is_freeze'] = 0;

        $cold_data = $this->check_goods($goods_list);
        $data['is_cold'] = $cold_data['is_cold'];
        $data['is_ice'] = $cold_data['is_ice'];
        $data['is_nom'] = $cold_data['is_nom'];
        if(!empty($data['is_ice'])||!empty($data['is_cold'])){
            $data['is_freeze'] = 1;
        }
        $goods_str = "";
        $all_goods_num = 0;
        foreach ($goods_list as $key => $value) {
            $goods_type = "";
            switch ($value['giving']){
                case 0:
                    //正常商品
                    break;
                case 1:
                    $goods_type = " [ 赠 ]";
                    break;
                case 2:
                    $goods_type = " [ 换 ]";
                    break;
                case 3:
                    $goods_type = " [ 抢 ]";
                    break;
                case 4:
                    $goods_type = " [ 促 ]";
                    break;
            }

            if($value['discount_price']>0){
                $this_goods_price = $value['discount_price'];
            }else{
                $this_goods_price = $value['goods_price'];
            }
            $goods_str = $goods_str.$value['goods_name'].$goods_type."\n货号:".$value['goods_sn']."\n价:".$value['goods_price']."x ".$value['real_num']." 折:".$value['goods_discount']." 计:".$value['real_num']*$this_goods_price."\n";
            $all_goods_num += $value['real_num'];
        }
        //查询商品退款信息
        $refund_str = "";
        $refund_num = 0;
        $refund_price = 0;
        //$refund_detail = M("refund_detail")->where('order_id ='.$order_id)->select();
        $refund_detail = M()->field('refund.goods_name,refund.refund_number,refund.refund_amount,goods.goods_price')->
        table('sdx_refund_detail as refund,sdx_order_goods as goods')->where('refund.goods_id = goods.goods_id AND refund.order_id = goods.order_id AND refund.order_id ='.$order_id)->select();
        if($refund_detail){
            $refund_str = "\n============退货信息============\n";
            foreach ($refund_detail as $value){
                $refund_str = $refund_str.$value['goods_name']."\n数量:".$value['refund_number']." 价:".$value['goods_price']." 计:".$value['refund_amount']."\n";
                $refund_num = $refund_num + $value['refund_number'];
                $refund_price = $refund_price + $value['refund_amount'];
            }
        }

        $data['goods_info'] = "============商品信息============\n".$goods_str."配货合计：".$all_goods_num."\n".$refund_str;

        $data["content"] = "订单编号：".$order['order_sn']."
客户名称：".$order['consignee']."
联系电话：".$order['mobile']."
客户备注：".$order['postscript']."
配送地址：".$order['address'];
//        echo $data["content"];
//        exit();


        returnApiSuccess($data,"已返回数据");
    }


    /**
     * 设置商品选中状态
     * rui poptser@foxmail.com 2016-10-21 14:43:47
     */
    // TODO 修改商品选中状态 set_select
    public function set_select(){
        $wp_userid=I('post.user_id','intval');  //用户ID
        $order_id     =I('post.order_id','intval');     //订单ID
        $goods_id     =I('post.goods_id','intval');     //商品ID
        if(empty($wp_userid)||empty($order_id)||empty($goods_id)){
            returnApiError('参数错误');
        }
        $this->check_user($wp_userid);

        $wid = $this->get_user_wid_identity($wp_userid);

        $selected = M("order_goods")->where("order_id =".$order_id." AND goods_id =".$goods_id)->getField("selected");
        if($selected==0){
            M("order_goods")->where("order_id =".$order_id." AND goods_id =".$goods_id)->setField("selected",1);
            $data['selected'] = 1;
        }else{
            M("order_goods")->where("order_id =".$order_id." AND goods_id =".$goods_id)->setField("selected",0);
            $data['selected'] = 0;
        }

        returnApiSuccess($data,"修改成功");
    }

    /**
     * 售后商品处理
     * rui poptser@foxmail.com 2016-10-12 10:44:05
     * handle_data goods_id type(1,2) number
     */
    // TODO 售后商品处理 handle_goods

    public function handle_goods(){
        //returnApiError("已暂停使用此功能，请使用新版拣货端");
        $order_id = I('post.order_id','intval');    //订单号
        $user_id = I('post.user_id','intval');
        $this->check_user($user_id);    //检查用户
        $wid = $this->get_user_wid_identity($user_id);

        $update = I("post.handle_data");
        $update = str_replace('&quot;','"',$update);

        $url=C("SDX_SEND_DOMIANURL")."index.php?m=admin&c=Store&a=refund&api=skip";
        $param['order_id'] = $order_id;

        $paramsss = A("Distribution")->get_admin_user_name($user_id);
        $param['admin_user'] = $paramsss['user_name'].":".$paramsss['phone'];
//        echo json_encode($paramsss);
//        exit;


        $Json_Data = json_decode($update, true);

        if($Json_Data){
            //json 解析成功
            $order_info = M("order_info")->where("order_status !=2 AND order_id = ".$order_id." AND wid =".$wid)->find();
            if($order_info){
                //订单状态正常，在配送中
                //查询此单商品剩余数量
                $sever_goods_list = $this->get_goods_list_real($order_id);

                //判断此有无提交数量超出实际商品剩余量的

                foreach ($Json_Data as $key=>$value){
                    $all_action = $value['lack']+$value['bad']+$value['back'];
                    $goods_real_list = array();
                    foreach ($sever_goods_list as $key2=>$value2){
                        if($value['rec_id']==$value2['rec_id']){
                            if($value2['real_num']<$all_action){
                                returnApiError("商品：".$value2['goods_name']."最大可操作数量为:".$value2['real_num']);
                            }
                        }
                        $goods_real_list[] = $value2['rec_id'];
                    }
                    foreach ($sever_goods_list as $key2=>$value2){
                        if(!in_array($value['rec_id'],$goods_real_list)){
                            returnApiError("商品：".$value['name']."最大可操作数量错误");
                        }
                    }
                }





                $lack_goods_list = array(); //缺货退款商品列表
                $bad_goods_list = array(); //次品退款商品列表
                $back_goods_list = array(); //退货退款商品列表


                $re_msg = null;
                foreach ($Json_Data as $key=>$value){

                    $goods_list= array();
                    $goods_info = M("order_goods")->field("discount_price,goods_id,act_id,rec_id,goods_name,goods_price,goods_sn,goods_number")
                        ->where("order_id = ".$order_id." AND rec_id ='".$value['rec_id']."'")->find();
                    $goods_list['goods_id'] = $goods_info['goods_id'];
                    $goods_list['rec_id'] = $goods_info['rec_id'];
                    $goods_list['act_id'] = $goods_info['act_id'];
                    if($goods_info['discount_price']>0){
                        $goods_list['goods_price'] = $goods_info['discount_price'];
                    }else{
                        $goods_list['goods_price'] = $goods_info['goods_price'];
                    }
                    $goods_list['goods_name'] = urlencode($goods_info['goods_name']);;
                    $goods_list['goods_sn'] = $goods_info['goods_sn'];
                    $goods_list['goods_number'] = $goods_info['goods_number'];

//                    dump($goods_list);
//                    exit();

                    if($value['lack']>0){
                        //加入缺货退款列表
                        $goods_list['cnt'] = $value['lack'];
                        array_push($lack_goods_list,$goods_list);
                        if($value['lack_remark']){
                            $refund_note_lack = $value['lack_remark'];
                        }
                    }
                    if($value['bad']>0){
                        //加入次品退款列表
                        $goods_list['cnt'] = $value['bad'];
                        $goods_list['cnt2'] = $value['bad'];
                        //dump($_FILES[$value['bad_photo']]['size']);
                        if($_FILES[$value['bad_photo_name']]['size']>100) {
                            $path = "uploads/refund_pic/" . rand(10000000, 99999999) . "." . end(explode('.', $_FILES[$value['bad_photo_name']]['name']));//接收文件目录
                            Ali_ossApi::upload($path, $_FILES[$value['bad_photo_name']]['tmp_name']);
                            $goods_list['photo'] = $path;
                        }
                        array_push($bad_goods_list,$goods_list);
                        if($value['bad_remark']){
                            $refund_note_bad = $value['bad_remark'];
                        }
                    }
                    if($value['back']>0){
                        //加入退款退款列表
                        $goods_list['cnt'] = $value['back'];
                        array_push($back_goods_list,$goods_list);
                        if($value['back_remark']){
                            $refund_note_back = $value['back_remark'];
                        }


                    }
                }
//                dump($bad_goods_list);
//                exit();

                //执行缺货退款操作
                if(count($lack_goods_list)>0){
                    $param['goods_list'] = json_encode($lack_goods_list);
                    $param['refund_type'] = '缺货退款';
                    $param['refund_amount'] = '';
                    $param['user_name'] = $param['admin_user'];
                    $param['refund_note'] = $refund_note_lack;
                    //dump($param);
                    //exit();
                    $lack_state = $this->rui_http_post($url,$param);
                    //dump($lack_state);
                    if($lack_state["error"]){
                        $re_msg=$re_msg."缺货退款 ".$lack_state["error"];
                    }
                }
                //执行次品退款操作
                if(count($bad_goods_list)>0){



                    $param['goods_list'] = json_encode($bad_goods_list);
                    $param['refund_type'] = '次品退款';
                    $param['refund_amount'] = '';
                    $param['user_name'] = $param['admin_user'];
                    $param['refund_note'] = $refund_note_bad;
                    $bad_state = $this->rui_http_post($url,$param);
                    if($bad_state["error"]){
                        $re_msg=$re_msg."次品退款 ".$bad_state["error"];
                    }
                }
                //执行退货退款操作
                if(count($back_goods_list)>0){
                    $param['goods_list'] = json_encode($back_goods_list);
                    $param['refund_type'] = '退货退款';
                    $param['refund_amount'] = '';
                    $param['user_name'] = $param['admin_user'];
                    $param['refund_note'] = $refund_note_back;
                    $back_state = $this->rui_http_post($url,$param);
                    //dump($back_state);
                    if($back_state["error"]){
                        $re_msg=$re_msg."退货退款 ".$back_state["error"];
                    }
                }
                if($re_msg){
                    returnApiError("部分商品操作失败\n".$re_msg);
                }else{
                    returnApiSuccess(null,"退款成功");
                }
            }else{
                returnApiError("订单不存在/不在配货状态/非本仓库");
            }
        }else{
            returnApiError("数据组错误");
        }
    }

    /**
     * post 提交进行退款
     * @param $url
     * @param $param
     * @return mixed
     */
    private function rui_http_post($url, $param){
        $post_file=false;
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            $res = json_decode($sContent,true);
            if($res['error']){
                return $res;
            }else{
                return $res;
            }
        }else{
            return false;
        }
    }
    /**
     * 根据订单ID获取订单里面的原始商品（未退款之前的）
     * rui
     * @param $order_id
     * @return mixed
     */
    private function get_goods_list_by_order($order_id,$no_gift=false){
        if($no_gift){
            $where['order_id'] = $order_id;
            $where['giving'] = array("neq",1);
            $order_goods = M("order_goods")->where($where)->select();
        }else{
            $order_goods = M("order_goods")->where(array("order_id"=>$order_id))->select();
        }

        foreach ($order_goods as $key=>$value){
            $order_goods[$key]['goods_sn'] = trim($value['goods_sn']);
        }

        return $order_goods;
    }

    /**
     * 查询订单的退款商品记录
     * rui
     * @param $order_id
     * @return mixed
     */
    private function get_refund_goods_list($order_id){
        $refund_detail = M("refund_detail")->field("order_goods_id,sum(refund_number) as refund_number ,sum(surplus_number) as surplus_number,goods_id,goods_name,goods_sn ")->where(array("order_id"=>$order_id))->group('order_goods_id')->select();
        //dump(M("refund_detail")->getlastsql());
        return $refund_detail;
    }

    /**
     * TODO 获取订单内剩余商品数
     * rui
     * @param $order_id
     * @return mixed
     */
    public function get_goods_list_real($order_id,$no_gift =  false){
        $buy_goods_list = $this->get_goods_list_by_order($order_id,$no_gift);
        //dump($buy_goods_list);

        $refund_goods_list = $this->get_refund_goods_list($order_id);
        //dump($refund_goods_list);
//        exit();
        foreach ($buy_goods_list as $key=>$value){
            $buy_goods_list[$key]['cat_id'] = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField('cat_id');
            $edit_goods = true;
            foreach ($refund_goods_list as $key2=>$value2){
                if($value['rec_id']==$value2['order_goods_id']){
                    $buy_goods_list[$key]['real_num'] = $value['goods_number']-$value2['refund_number'];
                    $edit_goods = false;
                }
            }
            if($edit_goods){
                $buy_goods_list[$key]['real_num'] = $value['goods_number'];
            }
            if($buy_goods_list[$key]['real_num']<1){
                unset($buy_goods_list[$key]);
            }
        }
        //dump($buy_goods_list);
        //echo "ddddddddd";
        //exit();
        return $buy_goods_list;
    }


    /**
     * TODO 获取预警URl  web
     * rui
     *
     */
    public function get_warn_url(){
        $data['url'] = C("SDX_SEND_DOMIANURL")."admin/customer_service.php?act=main&app_action=1";
        returnApiSuccess($data,"已返回数据");
    }
    /**
     * TODO 获取未质检预警URl  web
     * rui
     *
     */
    public function get_quality_url(){
        $data['url'] = C("SDX_SEND_DOMIANURL")."admin/customer_service.php?page=1&type=1001&app_action=1";
        returnApiSuccess($data,"已返回数据");
    }

    /**
     * TODO 直接获取订单详情页 web
     * rui
     */
    public function get_order_web(){
        $order_id = $_POST['order_id'];
        $order_num = $_POST['order_num'];

        if(!empty($order_id)){

            if(strlen($order_id) > 9){
                //扫出订单ID大于9，按订单编号查询
                if(strlen($order_id) > 19){
                    //扫出订单ID大于19，按订单编号加分袋信息查询
                    $where['order_sn'] = substr($order_id, 0, 19);
                }else{
                    $where['order_sn'] = $order_id;
                }
                $order_id = M("order_info")->where($where)->getField('order_id');
            }
        }elseif(!empty($order_num)){
            $order_id = M("order_info")->where("order_sn like '%".$order_num."'")->getField('order_id');

        }else{
            //returnApiError($order_num);
            returnApiError("订单ID/订单号后8位为空");
        }

        if(!empty($order_id)){
            $data['url'] = C("SDX_SEND_DOMIANURL")."admin/order.php?act=info&order_id=".$order_id."&app_action=1";
            returnApiSuccess($data,"已返回数据");
        }else{
            returnApiError("订单ID为空");
        }
    }
    /**
     * todo 获取未出仓/应回仓订单概览信息
     * rui
     */
    public function un_outgo_survey(){
        $action = $_POST['action'];   //操作类型（1 未出仓  2应回仓）
        $user_id = $_POST['user_id'];   //用户ID


        $wData = M("zoning_cate")->field("id,name")->select();
        foreach ($wData as $key=>$value){
            $wdrlist = M("warehouse_deliver_region")->where(array("zoning_id"=>$value['id']))->getField("id",true);
            if(count($wdrlist)>0){
                $wData[$key]['wData'] = implode(",",$wdrlist);
            }
        }
        //dump($wData);
        $company_array = M("distribution_company_user")->where(array("user_id"=>$user_id))->getField("company_id",true);
        if(!empty($company_array)){
            $where['distribution_company_id'] = array("in",$company_array);
        }
        $where['shipping_id'] = 3;                                  //配送单
        $where['freeze_status'] = 0;                                //非问题单
        $where['order_status'] = array("neq",2);                    //订单未取消
        $where['pay_status'] = array("in","2,3");                   //支付状态为已支付/部分退款
        $where['wid'] = $this->get_user_wid_identity($user_id);     //仓库ID
        $where['shipping_status'] = array("neq",2);                 //订单未配送完成
        //$where['196_admin_id'] = 0;

        if($action==1){
            $where['sorting_id'] = array("neq",0);      //已有配送员
            //$where['shipping_status'] = 5;              //订单状态为已完成配货
            $where['outgo'] = 0;                        //未出仓
            //$where['quality_id'] = array("neq",0);     //已质检
        }elseif($action==2){
            $where['outgo'] = 2;    //应回仓
        }else{
            returnApiError("未知操作");
        }


        $order_info = M('order_info');


        //统计数据start
        $data['ready_num'] = 0;     //待出仓，准备就绪

        $all_order_list = $order_info->where($where)->getField("order_id",true);
        //dump($all_order_list);

        $data['all_num'] = count($all_order_list); //所有未完成订单

        if($action==1){
            $where['shipping_status'] = 5;
            $where['quality_id'] = 0;
        }

        $data['unquality_num'] = $order_info->where($where)->count();    //配货完成未质检



        foreach ($all_order_list as $key=>$value){
            $order_bag_info = null;
            //$order_bag_info = S("order_bag_".$value);
            if($order_bag_info) {
                $scan_info = true;
                foreach ($order_bag_info as $key2 => $value_s) {
                    if ($value_s['is_scan'] == 0) {
                        $scan_info = false;
                    }
                }
                if ($scan_info) {
                    $data['ready_num'] ++;
                }
            }
        }
        //统计数据end


        $where['_string'] =  "distribution_company_area is null";   //没有第三方配送商物流点
        $re_data = array();

        foreach ($wData as $wKey=>$wValue) {
            if(empty($wValue['wData'])){
                continue;
            }
            $where['wdr_id'] = array("in",$wValue['wData']);
            $one_ready_num = 0;

            if($action==1){
                $where['shipping_status'] = array("neq",2);
                unset($where['quality_id']);
            }

            $unquality_num = 0;
            $one_order_list = $order_info->where($where)->field("order_id,quality_id")->select();
            $sql = $order_info->getLastSql();
            $order_num = count($one_order_list);    //本区域内订单数
            foreach ($one_order_list as $key=>$value){
                $k3cn_sn = M("order_info")->where(array("order_id"=>$value['order_id']))->getField("k3cn_sn");
                if(empty($k3cn_sn)){
                    $order_bag_info = S("order_bag_".$value['order_id']);
                }else{
                    $order_bag_info = $this->newGetS("order_bag_".$value['order_id']);
                }

                //$order_bag_info = S("order_bag_".$value['order_id']);
                if($order_bag_info) {
                    $scan_info = true;
                    foreach ($order_bag_info as $key2 => $value_s) {
                        if ($value_s['is_scan'] == 0) {
                            $scan_info = false;
                        }
                    }
                    if ($scan_info) {
                        $one_ready_num ++;
                    }
                }else{
                    //还无法出仓，判断是否质检
                    if($value['quality_id']==0){
                        $unquality_num++;
                    }
                }
            }
            if($order_num>0){
                $one_data = array(
                    "id" => $wValue['id'],
                    "sql" => $sql,
                    "name" => $wValue['name'],
                    "num" => $order_num,                //总订单数
                    "unquality_num" => $unquality_num,  //未质检数
                    "ready_num" => $one_ready_num   //可出仓订单数
                );
                array_push($re_data,$one_data);
            }
        }



        unset($where['wdr_id']);
        unset($where['_string']);
        $where['distribution_company_area'] =  array("neq","");   //有第三方配送商物流点
        $dis_area_list = $order_info->where($where)->field("distribution_company_area")->group("distribution_company_area")->select();



        foreach ($dis_area_list as $key=>$value){
            $where['distribution_company_area'] = $value['distribution_company_area'];
            $one_ready_num = 0;
            $one_order_list = $order_info->where($where)->field("order_id,quality_id")->select();
            $order_num = count($one_order_list);
            $unquality_num = 0;
            //dump(microtime());
            foreach ($one_order_list as $keys=>$values){
                //$order_bag_info = null;
                //$order_bag_info = S("order_bag_".$values['order_id']);


                $k3cn_sn = M("order_info")->where(array("order_id"=>$values['order_id']))->getField("k3cn_sn");
                if(empty($k3cn_sn)){
                    $order_bag_info = S("order_bag_".$values['order_id']);
                }else{
                    $order_bag_info = $this->newGetS("order_bag_".$values['order_id']);
                }

                if($order_bag_info) {
                    $scan_info = true;
                    foreach ($order_bag_info as $key2 => $value_s) {
                        if ($value_s['is_scan'] == 0) {
                            $scan_info = false;
                        }
                    }
                    if ($scan_info) {
                        $one_ready_num ++;
                    }else{
                        //还无法出仓，判断是否质检
                        if($values['quality_id']==0){
                            $unquality_num++;
                        }
                    }
                }
            }

            if($order_num>0){
                $one_data = array(
                    "id" => $value['distribution_company_area'],
                    "name" => $value['distribution_company_area']."->极客物流点",
                    "num" => $order_num,
                    "unquality_num" => $unquality_num,
                    "ready_num" => $one_ready_num
                );
                array_push($re_data,$one_data);
            }
        }

        if(empty($re_data)){
            returnApiError("无数据");
        }else{
            $data['list_area'] = $re_data;
            returnApiSuccess($data,"已返回数据");
        }
    }

    /**
     * todo 根据区域获取未出库/应回库订单组
     * rui
     */
    public function un_outgo(){
        $action = $_POST['action'];   //操作类型（1 未出仓  2应回仓）
        $area_id = $_POST['area_id'];   //仓库区域ID
        $user_id = $_POST['user_id'];   //
        if(empty($area_id)){
            returnApiError("area_id 错误");
        }
        if(!is_numeric($area_id)){
            $where['distribution_company_area'] = $area_id;    //按区域显示订单
        }else{
            $wdrlist = M("warehouse_deliver_region")->where(array("zoning_id"=>$area_id))->getField("id",true);
            if(count($wdrlist)>0){
                $wdr_id = implode(",",$wdrlist);
            }else{
                returnApiError("此大区未关联配送区域");
            }
            $where['wdr_id'] = array("in",$wdr_id);
            $where['_string'] =  "distribution_company_area is null";   //没有第三方配送商物流点
        }



        $company_array = M("distribution_company_user")->where(array("user_id"=>$user_id))->getField("company_id",true);
        if(!empty($company_array)){
            $where['distribution_company_id'] = array("in",$company_array);
        }
        //$where['196_admin_id'] = 0;    //`shipping_status` <> 2
        $where['shipping_id'] = 3;    //配送单
        $where['shipping_status'] = array("neq",2);    //未收货确认
        $where['freeze_status'] = 0;                                //非问题单
        $where['order_status'] = array("neq",2);    //订单未取消
        $where['pay_status'] = array("in","2,3");   //支付状态为已支付/部分退款
        $where['wid'] = $this->get_user_wid_identity($user_id);   //仓库ID
        if($action==1){
            $where['sorting_id'] = array("neq",0);      //已有配送员
            $where['outgo'] = 0;    //未出仓
            //$where['shipping_status'] = 5;              //订单状态为已完成配货
            $where['shipping_status'] = array("neq",2);              //订单未完成配送
            //$where['quality_id'] = array("neq",0);     //已质检
        }elseif($action==2){
            $where['outgo'] = 2;    //应回仓
            //$where['shipping_status'] = 0;              //订单状态为未发货状态
        }else{
            returnApiError("未知操作");
        }



        $data['list'] =$list= M("order_info")->
        field('shipping_status,quality_id,order_id,order_sn,batch_no,best_time,best_time_start,wdr_id,wid,distribution_company_id')
            ->where($where)->order('best_time asc')->select();

        //$sql = M("order_info")->getLastSql();

        if(count($list)>0){
            foreach ($data['list'] as $key=>$vaule){
                if($vaule['batch_no']>0){
                    $order_where_sub = "batch_no ='".$vaule['batch_no']."' AND TO_DAYS(from_unixtime(best_time)) = TO_DAYS(from_unixtime(".$vaule['best_time']."))";
                    $order_num=M("order_info")->where($order_where_sub)->count(); //查询是否有分单
                    if($order_num>1){
                        $data['list'][$key]['sub']= 1;
                    }else{
                        $data['list'][$key]['sub']= 0;
                    }
                }else{
                    $data['list'][$key]['sub']= 0;
                }

//                if($user_id!=190){
//                    $goods_list = $this->sh_goods_list($vaule['order_id'],$vaule['wid'],true);
//                    $cold_data = $this->check_goods($goods_list);
//                    $data['list'][$key]['is_cold'] = $cold_data['is_cold'];
//                    $data['list'][$key]['is_ice'] = $cold_data['is_ice'];
//                    $data['list'][$key]['is_nom'] = $cold_data['is_nom'];
//                }else{
                $data['list'][$key]['is_cold'] = 0;
                $data['list'][$key]['is_ice'] = 0;
                $data['list'][$key]['is_nom'] = 0;
                //}

                $data['list'][$key]['best_time']= date('Y-m-d H:i',$vaule['best_time_start'])." - ".date('Y-m-d H:i',$vaule['best_time']);
                $wdr_name = S("wdr_name_".$vaule['wdr_id']);
                if($wdr_name){
                    $data['list'][$key]['area']= $wdr_name;
                }else{
                    $wdr_name = M("warehouse_deliver_region")->where(array("id"=>$vaule['wdr_id']))->getField("name");
                    S("wdr_name_".$vaule['wdr_id'],$wdr_name,3600);
                    $data['list'][$key]['area']= $wdr_name;
                }

                $distribution_company_name = S("distribution_company_".$vaule['distribution_company_id']);
                if($distribution_company_name){
                    $data['list'][$key]['company']= $distribution_company_name;
                }else{
                    $distribution_company_name = M("distribution_company")->where(array("id"=>$vaule['distribution_company_id']))->getField("lite_name");
                    S("distribution_company_".$vaule['distribution_company_id'],$distribution_company_name,3600);
                    $data['list'][$key]['company']= $distribution_company_name;
                }
                $k3cn_sn = M("order_info")->where(array("order_id"=>$vaule['order_id']))->getField("k3cn_sn");
                if(empty($k3cn_sn)){
                    $order_bag_info = S("order_bag_".$vaule['order_id']);
                }else{
                    $order_bag_info = $this->newGetS("order_bag_".$vaule['order_id']);
                }
                //$order_bag_info = $this->newGetS("order_bag_".$vaule['order_id']); // 获取缓存
                //dump($this->newGetS("order_bag_773352"));
                $data['list'][$key]['is_check_all'] = 1;
                if($order_bag_info){
                    $scan_info = "未确认袋数：";
                    foreach ($order_bag_info as $key2=>$value_s){
                        if($value_s['is_scan']==0){
                            //未选中的单 常温0 冷藏1 冷冻2
                            if($value_s['type']==1){
                                $type = "冷藏";
                            }elseif($value_s['type']==2){
                                $type = "冷冻";
                            }else{
                                $type = "常温";
                            }
                            $scan_info .= "\n{$type} 袋号:{$value_s['current']}";
                            $data['list'][$key]['is_check_all'] = 0;
                        }
                    }
                    if($scan_info == "未确认袋数："){
                        $scan_info = "可以出仓了";
                    }
                    $data['list'][$key]['all_bag'] = $value_s['all'];
                }else{
                    $data['list'][$key]['all_bag'] = 0;

                    if($vaule['shipping_status']==3){
                        $scan_info = "未完成配货";
                    }else{
                        if($vaule['quality_id']>0){
                            $scan_info = "未打印质检单";
                        }else{
                            $scan_info = "未质检通过";
                        }
                    }


                    $data['list'][$key]['is_check_all'] = 0;
                }
                $data['list'][$key]['scan_info'] = $scan_info;

            }
            //$data['sql'] = $sql;
            returnApiSuccess($data,"已经返回数据");
        }else{
            returnApiError("(～￣▽￣)～没有找到记录");
        }
    }

    /**
     * todo 出仓/回仓 操作
     * rui
     */
    public function outgo_action(){
        $action2      = $_POST['action'];        //操作类型（1 未出仓  2应回仓）
        $user_id     = $_POST['user_id'];       //用户ID
        $order_str = $_POST['order_array'];     //订单ID组，多个以，号分割
        $driver_name = $_POST['driver_name'];   //司机姓名
        $car_sn = $_POST['car_sn'];             //车牌号
        $go_time = $_POST['go_time'];           //出发司机
        $to_time = $_POST['to_time'];           //预期到达司机
        $quality = $_POST['quality'];           //返回状态

        $run_ing = S("outgo_action_".$user_id);
        if(!empty($run_ing)){
            returnApiError("访问频率过快，间隔5秒");
        }else{
            S("outgo_action_".$user_id,999,5);
        }

        if($action2==1){
            if(empty($driver_name)||empty($car_sn)|empty($go_time)||empty($to_time)){
                returnApiError("部分数据为空");
            }
        }
        $company_array = M("distribution_company_user")->where(array("user_id"=>$user_id))->getField("company_id",true);
        if(!empty($company_array)){
            $where['distribution_company_id'] = array("in",$company_array);
        }

        $order_array = explode(",",$order_str);
        array_filter($order_array);
        $where['order_status'] = array("neq",2);    //订单未取消
        //$where['196_admin_id'] = 0;    //订单未取消
        $where['pay_status'] = array("in","2,3");   //支付状态为已支付/部分退款
        $where['wid'] = $this->get_user_wid_identity($user_id);   //仓库ID
        $where['shipping_id'] = 3;    //配送单
        if($action2==1){
            //未出仓
            $where['shipping_status'] = 5;
            $where['outgo'] = 0;
            $where['quality_id'] = array("neq",0);     //已质检
            $where['freeze_status'] = 0;                                //非问题单
            $data['outgo'] =  1;
            $data['outgo_id'] =  $user_id;
            $data['outgo_time'] =  gmtime();
            $action = "订单已出仓<br/>司机:".$driver_name." 车牌号:".$car_sn." 出发时间:".$go_time." 预期到达时间:".$to_time;
        }elseif($action2==2){
            $where['outgo'] = 2;    //应回仓
            $where['freeze_status'] = 0;                                //非问题单
            $data['station'] = 0;
            $data['station_id'] = 0;
            $data['station_time'] = 0;
            $data['outgo'] =  0;
            $data['unoutgo_id'] =  $user_id;
            $data['unoutgo_time'] =   gmtime();

            if($quality==1){
                $data['shipping_status'] =  5;
                $action="订单已回仓，无需质检,无需打印分袋单";

            }else{
                $action = "订单已回仓";
                $data['shipping_status'] =  0;
                $data['quality_id'] = 0;
                $data['quality_time'] = 0;
                $data['sorting_id'] = 0;
                $data['sorting_time'] = 0;
            }
        }else{
            returnApiError("未知操作");
        }
        if(count($order_array)>0){
            $all_order_send_res = "";
            $i=0;
            foreach ($order_array as $key=>$value){
                $k3cn_sn = M("order_info")->where(array("order_id"=>$value))->getField("k3cn_sn");
                if($action2==2){
                    if($quality!=1){
                        //未选中无需质检，则不清空质检单信息
                        //S("order_bag_".$value,null);
                        if(empty($k3cn_sn)){
                            S("order_bag_".$value,null);
                        }else{
                            $this->newSetS("order_bag_".$value,null);
                        }

                        M("order_info_ext")->where(array("order_id"=>$value))->setField("bag_num",0);
                    }
                }
                //先不使用
                if($action2==100){
                    //出仓时，判断所有分袋信息
                    $is_scan_num = 0;
                    //$order_bag_info = S("order_bag_".$value);
                    if(empty($k3cn_sn)){
                        $order_bag_info = S("order_bag_".$value);
                    }else{
                        $order_bag_info = $this->newGetS("order_bag_".$value);
                    }

                    if($order_bag_info){
                        foreach ($order_bag_info as $value_s){
                            if($value_s['is_scan']==1){
                                $is_scan_num++;
                            }
                        }
                        if($order_bag_info[0]['all']!=$is_scan_num){
                            //未全部选中，不推送订单
                            break;
                        }
                    }
                }


                $push_bsc = 1;
                $where['order_id'] = $value;
                $order_info = M("order_info")->where($where)->find();
                if(empty($order_info)){
                    $all_order_send_res.= M("order_info")->where(array("order_id"=>$value))->getField("order_sn")." 失败\n";
                    continue;
                }
                //上鲜送已停止活动



                if($action2==1){
                    $log_text = "已出仓";
                    //出仓成功，修改金蝶订单为出库单
                    $KingdeeService = new KingdeeService();
                    $KingdeeJosn = $KingdeeService->changeToOutbound($value);
                    //returnApiError($KingdeeJosn);
                }else{
                    //回仓单
                    $KingdeeService = new KingdeeService();
                    $KingdeeJosn = $KingdeeService->BackToWarehouseGoods($value,$order_info['wid']);
                    $log_text = "已回仓";
                }
                $KingdeeArray = json_decode($KingdeeJosn,true);
                //dump($KingdeeJosn);
                if($KingdeeArray['code']==200){
                    A("Distribution")->record_logistics($value,$order_info['shipping_status'],$log_text);
                    $flag = true;
                    //极客配送的订单推送到极客配送系统
                    if($action2 == 1 && empty($order_info['196_admin_id'])){
                        $send_other_service = false;
                        $chucang_user_list = C('gk_chucang_user_id');
                        if(in_array($user_id,$chucang_user_list) && !in_array($order_info['shipping_extend_status'],array(5))){
                            $send_other_service = true;
                            $this->write_log("gk test data: begin send to gk:",'gk_shipping');
                            $flag = $this->send_order_to_gk('',$order_info,$user_id,false);
                        }
                        $bd_chucang_user_list = C('bd_chucang_user_id');
                        if(in_array($user_id,$bd_chucang_user_list)){
                            $send_other_service = true;
                            $this->write_log("bd test data: begin send to bd:",'bd_shipping');
                            $flag = $this->send_order_to_bd('',$order_info,$user_id,false);
                        }

                        $eleme_chucang_user_list = C('eleme_chucang_user_id');
                        if(in_array($user_id,$eleme_chucang_user_list)){
                            $send_other_service = true;
                            $this->write_log("eleme test data: begin send to eleme:",'eleme_shipping');
                            $flag = $this->send_order_to_eleme('',$order_info,$user_id,false);
                        }

                        $sf_chucang_user_list = C('sf_chucang_user_id');
                        if(in_array($user_id,$sf_chucang_user_list)){
                            $send_other_service = true;
                            $this->write_log("SF test data: begin send to SF:",'sf_shipping');
                            $flag = $this->send_order_to_sf('',$order_info,$user_id,false);
                        }
                        if($send_other_service === false){
                            //未推送到其他第三方平台的订单统一推送至物流平台
                            $this->write_log("SDX test data: begin send to SDX:",'sdx_bsc_ok');
                            $flag = $this->send_order_to_sdx('',$order_info,$user_id,false);
                        }

                    }

                    if($flag['error']==1){
                        if(!empty($all_order_send_res)){
                            $and = ";";
                        }else{
                            $and = "";
                        }
                        $all_order_send_res.= $and.$flag['msg'];
                        continue;
                    }
                    if(in_array($order_info['shipping_extend_type'],array('gk','bd','eleme','sf'))){
                        if($action2==2){
                            if($order_info['shipping_extend_status']==3){
                                $data['shipping_extend_status']=5;  //修改配送时间回仓
                            }elseif($order_info['shipping_extend_status']==2){
                                $data['shipping_extend_status']=4;  //撤销订单回仓
                            }
                        }
                    }
                    if(in_array($order_info['shipping_extend_type'],array('sdx'))){
                        if($action2==2){
                            if($order_info['shipping_extend_status']==7){
                                $data['shipping_extend_status']=8;  //回仓
                            }
                        }
                    }
                    if($action2==1&&$user_id==423){
                        //上鲜送订单
                    }elseif($action2==1&&$user_id==103){
                        //文佳测试账号
                    }elseif($action2==1){
                        //非上鲜送订单，直接到站
                        //修改已到站
                        $data['station'] = 1;
                        $data['station_id'] = $user_id;
                        $data['station_time'] = gmtime();
                        $actions ="<br/>自动到站";
                    }
                    $Result = M("order_info")->where($where)->save($data);
                    if($Result){
                        $i++;
                        $a=array(
                            'order_id'=>$value,
                            'user_id'=>$user_id,
                            'order_status'=>$order_info['order_status'],
                            'shipping_status'=>$order_info['shipping_status'],
                            'pay_status'=>$order_info['pay_status'],
                            'to_user'=>1,
                            'action_note'=>$action.$actions." Kingdee SN:".$KingdeeArray['data']['Number']
                        );
                        A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
                    }
                }else{
                    returnApiError("金蝶返回错误信息:\n".$KingdeeArray['message']);
                }
            }

            if(!empty($all_order_send_res)){
                $data['show_send_msg'] = $all_order_send_res;
                returnApiSuccess($data,"一共".count($order_array)."个订单\n成功:".$i);
            }else{
                //returnApiError("dd");
                returnApiSuccess(null,"一共".count($order_array)."个订单\n成功:".$i);
            }

        }else{
            returnApiError("老板，勾选订单先");
        }
    }

    public function send_order_to_bd($order_id,$order,$user_id,$show_return=true){
        if(empty($order)){
            $where['order_id'] = $order_id;
            $order = M("order_info")->where($where)->find();
        }

        if(empty($order) && !empty($order_id)){
            if($show_return){
                returnApiError('配送订单不存在');
            }
        }
        if(empty($order)){
            return false;
        }
        //订单送货地址信息
        $province_name=M('region')->where('region_id ='.$order['province'])->getField('region_name');
        $city_name=M('region')->where('region_id ='.$order['city'])->getField('region_name');
        $district_name=M('region')->where('region_id ='.$order['district'])->getField('region_name');

        //获取订单商品信息
        $goods_field = "goods_id,goods_name as dish_name,goods_price as dish_unit_price,goods_number as dish_number,goods_price*goods_number as dish_total_price";
        $order_goods = M('order_goods')->field($goods_field)->where(array('order_id'=>$order['order_id']))->select();

        $product_price = 0;
        foreach ($order_goods as $key=>$value){
            $sum_refund_number = $this->get_goods_refund_num($order['order_id'],$value['goods_id']);
            if($value['dish_number']-$sum_refund_number<=0){
                unset($order_goods[$key]);
                continue;
            }
            $product_price += $value['dish_total_price'];
            unset($order_goods[$key]['goods_id']);
        }

        $order_goods = array_values($order_goods);
        $receiver_address = $province_name.$city_name.$district_name;
        if(!empty($order['address'])){
            $receiver_address .= $order['address'].$order['address_name'];
        }else{
            $receiver_address .= $order['sign_building'].$order['address_name'];
        }



        if($order['shipping_extend_status']==4){
            $order['order_sn'] = $this->get_repush_order_sn($order['order_sn'],'bd');
        }

        $_POST['store']=1;
        $order['order_amount'] = $order['order_amount']+$order['surplus']+$order['money_paid'];
        $order['order_amount'] = round($order['order_amount'],2);
        $order_detail = array(
            'product_price'=>$product_price,
            'products'=>$order_goods
        );



        $baidu_order_sequence = S('baidu_order_sequence'.date("d"));
        $count = $baidu_order_sequence[$order['order_id']];

//        $date = date('Y_m_d');
//        $count = S('baidu_order_index_'.$date);
//        if(empty($count)){
//            $count = 1;
//        }else{
//            $count++;
//        }
//        S('baidu_order_index_'.$date,$count,48*60*60);

        $order_time = localtotime($order['add_time']);
        $order_time_today = localtotime(gmtime());
        if(($order_time_today-$order_time)-(24*60*60*2)>0){
            $order_time = $order_time_today;
        }

        $order_shipping_info = array(
            'out_order_id' => $order['order_sn'],
            'order_index'=>$count,
            'user_phone' => $order['mobile'],
            'user_address' => $receiver_address,   //北京市工人体育馆
//            'user_address' => "北京市工人体育馆",   //北京市工人体育馆
            'user_name' => $order['consignee'],
            'user_longitude'  => $order['longitude'],  //116.457945
            'user_latitude'  => $order['latitude'],    //"39.931679"
//            'user_longitude'  => "116.457945",  //116.457945
//            'user_latitude'  => "39.931679",    //"39.931679"
            'wl_shop_id'=> C('bd_wl_shop_id'),
            'shop_phone'=>C('shop_phone'),
            'order_time'=>$order_time,
            'expect_time_mode'=>1,
            'expect_time_start' => $order['best_time_start'],
            'expect_time' => $order['best_time_start']+3600*1.5, //$order['best_time']
            'shop_price'=> "0.00",
            'user_price'=> "0.00",
            'user_total_price'=> $order ['order_amount'],
            'remark' => $order['postscript'],
            'pay_type'=>1,
            'source_name'=>C('bd_source'),
            'order_detail'=>$order_detail,
            'push_time'=>time(),
            'app_id'=>C('bd_app_id')
        );
        $this->write_log("bd test data: ".json_encode($order_shipping_info),'bd_shipping');
        //推送订单
        $Bd_Submit = new BaidushippingSubmit();
        $res = $Bd_Submit->postOrder($order_shipping_info);

        $this->write_log("bd test: ".json_encode($res),'bd_shipping');

        if($res['error_no']!=0){
            $error_msg = $Bd_Submit->get_post_error_msg();
            A('Baidushipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")出仓失败，".$error_msg[$res['error_no']]."(".$res['message'].")",array(),array(),false);
            if($show_return){
                returnApiError("百度配送订单推送不成功，订单(".$order['order_sn'].")出仓失败，".$error_msg[$res['error_no']]."(".$res['message'].")");
            }else{
                $return_data['error'] = 1;
                $return_data['msg'] = "订单(".$order['order_sn'].")出仓失败，".$res['message'];
                return $return_data;
            }
        }else{
            $order_data = array(
                'shipping_extend_type'=>'bd',
                'shipping_extend_status'=>0
            );
            M("order_info")->where(array('order_id'=>$order['order_id']))->save($order_data);

            $return_data = $res['result'];
            $shipping_extend_order_id = $return_data['order_id'];
            $this->save_shipping_extend_order_id($order['order_id'],$shipping_extend_order_id);
        }
        return true;
    }

    /**
     * 保存百度物流单号
     * @param $order_id
     * @param $shipping_extend_order_id
     */
    private function save_shipping_extend_order_id($order_id,$shipping_extend_order_id){
        if(!empty($shipping_extend_order_id)){
            if(!empty($order_id)){
                $extend_map = array('order_id'=>$order_id);
                $count = M('order_info_ext')->where($extend_map)->count();

                if($count>0){
                    M('order_info_ext')->where($extend_map)->setField('shipping_extend_order_id',$shipping_extend_order_id);
                }else{
                    $data = array();
                    $data['order_id'] = $order_id;
                    $data['shipping_extend_order_id'] = $shipping_extend_order_id;
                    M('order_info_ext')->add($data);
                }
            }
        }
    }

    /**
     * todo 推送订单到极客配送
     * @param $order_id
     * @param $order
     * @param $user_id
     * @param $show_return
     * @return bool
     */
    public function send_order_to_gk($order_id,$order,$user_id,$show_return=true){
        if(empty($order)){
            $where['order_id'] = $order_id;
            $order = M("order_info")->where($where)->find();
        }

        if(empty($order) && !empty($order_id)){
            if($show_return){
                returnApiError('配送订单不存在');
            }

        }
        if(empty($order)){
            return false;
        }
        //订单送货地址信息
        $province_name=M('region')->where('region_id ='.$order['province'])->getField('region_name');
        $city_name=M('region')->where('region_id ='.$order['city'])->getField('region_name');
        $district_name=M('region')->where('region_id ='.$order['district'])->getField('region_name');

        //获取订单商品信息
        $goods_field = "goods_id,goods_name as name,goods_price as price,goods_number as quantity,goods_price*goods_number as total";
        $order_goods = M('order_goods')->field($goods_field)->where(array('order_id'=>$order['order_id']))->select();

        $total_quantity = 0;
        $total_weight = 0;
        foreach ($order_goods as $key=>$value){
            $goods_id = $value['goods_id'];
            $goods_weight = M("goods")->where(array("goods_id"=>$goods_id))->getField("goods_weight");
            $sum_refund_number = $this->get_goods_refund_num($order['order_id'],$value['goods_id']);
            if($value['quantity']-$sum_refund_number<=0){
                unset($order_goods[$key]);
                continue;
            }
            $order_goods[$key]['value'] = $goods_weight;
            $order_goods[$key]['model'] = $goods_weight."kg";
            $order_goods[$key]['deliver_cid'] = 7;
            $total_quantity+=$value['quantity']-$sum_refund_number;
            $total_weight+=$goods_weight*($value['quantity']-$sum_refund_number);
            unset($order_goods[$key]['goods_id']);
        }
        $order_goods = array_values($order_goods);
//        $receiver_address = !empty($order['address'])?$order['address']:$order['address_name'];

        //$order_bag = S('order_bag_'.$order['order_id']);
        $k3cn_sn = M("order_info")->where(array("order_id"=>$order['order_id']))->getField("k3cn_sn");
        if(empty($k3cn_sn)){
            $order_bag = S("order_bag_".$order['order_id']);
        }else{
            $order_bag = $this->newGetS("order_bag_".$order['order_id']);
        }
        if(!empty($order_bag)){
            $order_goods = array();
            foreach ($order_bag as $order_item){
                $tmp_order_item = array();
                $type_name = $this->get_bag_type_name($order_item['type']);
                $tmp_order_item['name'] =$type_name.$order_item['current'];
                $tmp_order_item['price'] =1;
                $tmp_order_item['value'] =1;
                $tmp_order_item['quantity'] =1;
                $tmp_order_item['total'] =1;
                $tmp_order_item['model'] ='1kg';
                $tmp_order_item['deliver_cid'] =7;
                $tmp_order_item['product_no'] =$order['order_sn'].str_pad($order_item['all'],2,"0",STR_PAD_LEFT).str_pad($order_item['current'],2,"0",STR_PAD_LEFT).$order_item['type'];

                $order_goods[] = $tmp_order_item;
            }
        }
        $receiver_address = $province_name.$city_name.$district_name;
        $receiver_address .= $order['address'];
        if(!empty($order['sign_building'])){
            $receiver_address.= $order['sign_building'];
        }
        if(!empty($order['address_name'])){
            $receiver_address.= $order['address_name'];
        }

//        if(!empty($order['address'])){
//            $receiver_address .= $order['address'].$order['address_name'];
//        }else{
//            $receiver_address .= $order['sign_building'].$order['address_name'];
//        }

        if($order['shipping_extend_status']==4){
            $order['order_sn'] = $this->get_repush_order_sn($order['order_sn'],'gk');
        }

        $_POST['store']=1;
        $gk_chucang_user_list = C('gk_chucang_user_id');
        $gk_warehouse_list = array_flip($gk_chucang_user_list);

        $wid = $gk_warehouse_list[$user_id];

        $sender_info_list = C('gk_sender_info');
        $sender_info = $sender_info_list[$wid];
        //订单取货地址信息
        $sender_province_name=M('region')->where('region_id ='.$sender_info['sender_province'])->getField('region_name');
        $sender_city_name=M('region')->where('region_id ='.$sender_info['sender_city'])->getField('region_name');
        $sender_district_name=M('region')->where('region_id ='.$sender_info['sender_district'])->getField('region_name');

        $verify_code = A('Distribution')->get_order_receipt_code($order['order_id']);
        $order_shipping_info = array(
            'order_no' => $order['order_sn'],
            'receiver' => $order['consignee'],
            'receiver_telephone' => $order['mobile'],
            'receiver_province' => $province_name,
            'receiver_city' => $city_name,
            'receiver_district' => $district_name,
            'receiver_address' => $receiver_address,
//            'receiver_longitude'  => $order['longitude'],
//            'receiver_latitude'  => $order['latitude'],
//            'receiver_position_source'=>1,
            'sender'=>$sender_info['sender'],
            'sender_telephone'=>$sender_info['sender_telephone'],
            'sender_province'=>$sender_province_name,
            'sender_city'=>$sender_city_name,
            'sender_district'=>$sender_district_name,
            'sender_address'=>$sender_info['sender_address'],
            'payment_method' => '线上已支付',
            'total' => '0',
            'weight' => $total_weight,
            'quantity' => $total_quantity,
            'comment' => $order['postscript'],
            'products' =>$order_goods,
            'deliver_time' => date('Y-m-d H:i:s',$order['best_time_start']),
            'deliver_time_end' => date('Y-m-d H:i:s',$order['best_time']),
            'verify_code' =>$verify_code
        );
        $this->write_log("gk test data: ".json_encode($order_shipping_info),'gk_shipping');
        //推送订单
        $Gk_Submit = new GkshippingSubmit();
        $res = $Gk_Submit->postOrder($order_shipping_info);

        $this->write_log("gk test: ".json_encode($res),'gk_shipping');
        $i=0;
        while($res['result']=='fail' && $i<3){
            $res = $Gk_Submit->postOrder($order_shipping_info);
            $i++;
        }

//        if(!empty($order_id) && $res['result']=='fail'){
//            returnApiError("极客配送订单推送失败，".$res['info'].",请重新手动推送订单！");
//        }
//
//        if(!empty($order_id)){
//            returnApiSuccess('','极客配送订单推送成功');
//        }

        if($res['result']=='fail'){
            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")出仓失败，".$res['info'],array(),array(),false);
            if($show_return){
                returnApiError("极客配送订单推送不成功，订单(".$order['order_sn'].")出仓失败，".$res['info']);
            }else{
                $return_data['error'] = 1;
                $return_data['msg'] = "订单(".$order['order_sn'].")出仓失败，".$res['info'];
                return $return_data;
            }
        }else{
            $order_data = array(
                'shipping_extend_type'=>'gk',
                'shipping_extend_status'=>0
            );
            M("order_info")->where(array('order_id'=>$order['order_id']))->save($order_data);
        }

        return true;
    }

    private function get_bag_type_name($type){
        $name = "";
        switch ($type){
            case "1":
                $name="藏";
                break;
            case "2":
                $name="冻";
                break;
            case "0":
                $name="常";
                break;
        }
        return $name;
    }

    /**
     * todo 推送订单到蜂鸟配送
     * @param $order_id
     * @param $order
     * @param $user_id
     * @param $show_return
     * @return bool
     */
    public function send_order_to_eleme($order_id,$order,$user_id,$show_return=true){
        if(empty($order)){
            $where['order_id'] = $order_id;
            $order = M("order_info")->where($where)->find();
        }

        if(empty($order) && !empty($order_id)){
            if($show_return){
                returnApiError('配送订单不存在');
            }
        }
        if(empty($order)){
            return false;
        }
        //订单送货地址信息
        $province_name=M('region')->where('region_id ='.$order['province'])->getField('region_name');
        $city_name=M('region')->where('region_id ='.$order['city'])->getField('region_name');
        $district_name=M('region')->where('region_id ='.$order['district'])->getField('region_name');

        //获取订单商品信息
        $goods_field = "og.goods_id,og.goods_name as item_name,mp.user_price as item_price,og.goods_price as item_actual_price,og.goods_number as item_quantity";
        $order_goods = M('order_goods')
            ->alias('og')
            ->field($goods_field)
            ->join('left join '.C('DB_PREFIX').'member_price mp on og.goods_id=mp.goods_id')
            ->where(array('og.order_id'=>$order['order_id'],'mp.user_rank'=>1))
            ->select();

        $total_quantity = 0;
        $total_weight = 0;
        $order_total_amount = 0;
        $order_actual_amount = 0;
        foreach ($order_goods as $key=>$value){
            $goods_id = $value['goods_id'];
            $goods_weight = M("goods")->where(array("goods_id"=>$goods_id))->getField("goods_weight");
            $sum_refund_number = $this->get_goods_refund_num($order['order_id'],$goods_id);
            if($value['item_quantity']-$sum_refund_number<=0){
                unset($order_goods[$key]);
                continue;
            }
            $order_goods[$key]['item_quantity'] = $value['item_quantity']-$sum_refund_number;
            $order_goods[$key]['is_need_package'] = C('eleme_is_need_package');
            $order_goods[$key]['is_agent_purchase'] = C('eleme_is_agent_purchase');
            $total_quantity+=$value['item_quantity']-$sum_refund_number;
            $total_weight+=$goods_weight*($value['item_quantity']-$sum_refund_number);
            $order_total_amount+=($value['item_quantity']-$sum_refund_number)*$value['item_price'];
            $order_actual_amount+=($value['item_quantity']-$sum_refund_number)*$value['item_actual_price'];
            unset($order_goods[$key]['goods_id']);
        }

        $order_goods = array_values($order_goods);

        //$order_bag = S('order_bag_'.$order['order_id']);
        $k3cn_sn = M("order_info")->where(array("order_id"=>$order['order_id']))->getField("k3cn_sn");
        if(empty($k3cn_sn)){
            $order_bag = S("order_bag_".$order['order_id']);
        }else{
            $order_bag = $this->newGetS("order_bag_".$order['order_id']);
        }
        //$order_bag = $this->newGetS('order_bag_'.$order['order_id']);
        if(!empty($order_bag)){
            $order_goods = array();
            foreach ($order_bag as $order_item){
                $tmp_order_item = array();
                $type_name = $this->get_bag_type_name($order_item['type']);
                $tmp_order_item['item_id'] =$order['order_sn'].str_pad($order_item['all'],2,"0",STR_PAD_LEFT).str_pad($order_item['current'],2,"0",STR_PAD_LEFT).$order_item['type'];
                $tmp_order_item['item_name'] =$type_name.$order_item['current'];
                $tmp_order_item['item_quantity'] =1;
                $tmp_order_item['item_price'] =1;
                $tmp_order_item['item_actual_price'] =1;
                $tmp_order_item['is_need_package'] = C('eleme_is_need_package');
                $tmp_order_item['is_agent_purchase'] = C('eleme_is_agent_purchase');

                $order_goods[] = $tmp_order_item;
            }
        }

        $receiver_address = $province_name.$city_name.$district_name;
        $receiver_address .= $order['address'];
        if(!empty($order['sign_building'])){
            $receiver_address.= $order['sign_building'];
        }
        if(!empty($order['address_name'])){
            $receiver_address.= $order['address_name'];
        }
//        if(!empty($order['address'])){
//            $receiver_address .= $order['address'].$order['address_name'];
//        }else{
//            $receiver_address .= $order['sign_building'].$order['address_name'];
//        }

//        if($order['shipping_extend_status']==4){
//            $order['order_sn'] = $this->get_repush_order_sn($order['order_sn'],'emleme');
//        }

        $_POST['store']=1;
        $eleme_chucang_user_list = C('eleme_chucang_user_id');
        $eleme_warehouse_list = array_flip($eleme_chucang_user_list);

        $wid = $eleme_warehouse_list[$user_id];

        $transport_info_list = C('eleme_transport_info');
        $transport_info = $transport_info_list[$wid];

        $baidu_order_sequence = S('baidu_order_sequence'.date("d"));
        $count = $baidu_order_sequence[$order['order_id']];


        if($order['longitude']>$order['latitude']){
            $longitude = $order['longitude'];
            $latitude = $order['latitude'];
        }else{
            $longitude = $order['latitude'];
            $latitude = $order['longitude'];
        }

        $ts_best_time_start='';
        if(gmtime()<$order['best_time_start']){
            $ts_best_time_start=($order['best_time_start']+3600*1.5) * 1000;
        }

        $order_shipping_info = array(
            'transport_info' => $transport_info,
            'receiver_info' => array(
                'receiver_name' => $order['consignee'],
                'receiver_primary_phone' => $order['mobile'],
                'receiver_address' => $receiver_address,
                'receiver_longitude' => $longitude,
                'position_source' => $transport_info['position_source'],
                'receiver_latitude' => $latitude
            ),
            'items_json' => $order_goods,
            'partner_remark' => '食得鲜',
            'partner_order_code' => $order['order_sn'],     // 第三方订单号, 需唯一
            'notify_url' => C('eleme_notify_url'),     //第三方回调 url地址
            'order_type' => 1,
            'order_total_amount' => $order_total_amount,
            'order_actual_amount' => $order_actual_amount,
            'order_weight'=> $total_weight,
            'is_invoiced' => 0,
            'invoice' => C('eleme_invoice'),
            'order_payment_status' => 1,
            'order_payment_method' => 1,
            'goods_count' => $total_quantity,
            'is_agent_payment' => 0,
            'require_receive_time' => $ts_best_time_start,  //注意这是毫秒数
            'serial_number'=>$count
        );

        $this->write_log("eleme test data: ".json_encode($order_shipping_info),'eleme_shipping');
        //推送订单
        $Gk_Submit = new ElemeshippingSubmit();
        $res = $Gk_Submit->sendOrder($order_shipping_info);

        $this->write_log("eleme test: ".json_encode($res),'eleme_shipping');

        if((empty($res) || $res['code']!='200')){
            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")出仓失败，".$res['msg'],array(),array(),false);
            if($show_return){
                returnApiError("蜂鸟配送订单推送不成功，订单(".$order['order_sn'].")出仓失败，".$res['msg']);
            }else{
                $return_data['error'] = 1;
                $return_data['msg'] = "订单(".$order['order_sn'].")出仓失败，".$res['msg'];
                return $return_data;
            }
        }else{
            $order_data = array(
                'shipping_extend_type'=>'eleme',
                'shipping_extend_status'=>0
            );
            M("order_info")->where(array('order_id'=>$order['order_id']))->save($order_data);
        }

        return true;
    }

    /**
     * todo 推送订单到顺丰配送
     * @param $order_id
     * @param $order
     * @param $user_id
     * @param $show_return
     * @return bool
     */
    public function send_order_to_sf($order_id,$order,$user_id,$show_return=true){
        if(empty($order)){
            $where['order_id'] = $order_id;
            $order = M("order_info")->where($where)->find();
        }

        if(empty($order) && !empty($order_id)){
            if($show_return){
                returnApiError('配送订单不存在');
            }
        }
        if(empty($order)){
            return false;
        }
        //订单送货地址信息
        $province_name=M('region')->where('region_id ='.$order['province'])->getField('region_name');
        $city_name=M('region')->where('region_id ='.$order['city'])->getField('region_name');
        $district_name=M('region')->where('region_id ='.$order['district'])->getField('region_name');

        //获取订单商品信息
        $goods_field = "goods_id,goods_name,goods_price,goods_number";
        $order_goods = M('order_goods')->field($goods_field)->where(array('order_id'=>$order['order_id']))->select();

        $total_quantity = 0;
        $total_weight = 0;
        $order_total_amount = 0;
        $order_goods_temp = array();
        foreach ($order_goods as $key=>$value){
            $goods_id = $value['goods_id'];
            $goods_weight = M("goods")->where(array("goods_id"=>$goods_id))->getField("goods_weight");
            $sum_refund_number = $this->get_goods_refund_num($order['order_id'],$goods_id);
            if($value['goods_number']-$sum_refund_number<=0){
                unset($order_goods[$key]);
                continue;
            }
            $order_goods_temp[$key]['itemName'] = $value['goods_name'];
            $order_goods_temp[$key]['itemPrice'] = $value['goods_price'];
            $order_goods_temp[$key]['itemQty'] = $value['goods_number']-$sum_refund_number;
            $order_goods_temp[$key]['currency'] = 'CNY';
            $order_goods_temp[$key]['itemWeight'] = $goods_weight;
            $order_goods_temp[$key]['itemModel'] = '';
            $order_goods_temp[$key]['itemVolume'] = '';
            $order_goods_temp[$key]['itemMemo'] = '';

            $total_quantity+=$value['goods_number']-$sum_refund_number;
            $total_weight+=$goods_weight*($value['goods_number']-$sum_refund_number);
            $order_total_amount+=($value['goods_number']-$sum_refund_number)*$value['goods_price'];
            unset($order_goods[$key]['goods_id']);
        }

        $order_goods = array_values($order_goods_temp);

        //$order_bag = S('order_bag_'.$order['order_id']);
        $k3cn_sn = M("order_info")->where(array("order_id"=>$order['order_id']))->getField("k3cn_sn");
        if(empty($k3cn_sn)){
            $order_bag = S("order_bag_".$order['order_id']);
        }else{
            $order_bag = $this->newGetS("order_bag_".$order['order_id']);
        }
        //$order_bag = $this->newGetS('order_bag_'.$order['order_id']);
        if(!empty($order_bag)){
            $total_quantity = 0;
            $order_goods = array();
            foreach ($order_bag as $order_item){
                $tmp_order_item = array();
                $type_name = $this->get_bag_type_name($order_item['type']);
                $tmp_order_item['itemName'] =$type_name.$order_item['current'];
                $tmp_order_item['itemQty'] =1;
                $tmp_order_item['itemPrice'] =1;
                $tmp_order_item['currency'] = 'CNY';
                $tmp_order_item['itemWeight'] =0.0;
                $tmp_order_item['itemModel'] = '';
                $tmp_order_item['itemVolume'] = '';
                $tmp_order_item['itemMemo'] = '';
                $order_goods[] = $tmp_order_item;
                $total_quantity+=1;
            }
        }

        $receiver_address = $province_name.$city_name.$district_name;
        $receiver_address .= $order['address'];
        if(!empty($order['sign_building'])){
            $receiver_address.= $order['sign_building'];
        }
        if(!empty($order['address_name'])){
            $receiver_address.= $order['address_name'];
        }
//        if(!empty($order['address'])){
//            $receiver_address .= $order['address'].$order['address_name'];
//        }else{
//            $receiver_address .= $order['sign_building'].$order['address_name'];
//        }

        $_POST['store']=1;

        if($order['shipping_extend_status']==4){
            $order['order_sn'] = $this->get_repush_order_sn($order['order_sn'],'sf');
        }

        $baidu_order_sequence = S('baidu_order_sequence'.date("d"));
        $count = $baidu_order_sequence[$order['order_id']];

        $sf_config = C('SF_CONFIG');
        $sf_chucang_user_list = C('sf_chucang_user_id');
        $sf_warehouse_list = array_flip($sf_chucang_user_list);
        $wid = $sf_warehouse_list[$user_id];

        $transport_info_list = $sf_config['SHOP_INFO'];
        $transport_info = $transport_info_list[$wid];

        $order_shipping_info = array(
            'order'=>array(
                'orderNo'=>$order['order_sn'],
                'orderAmount'=>$order_total_amount,
                'payMethod'=>1,
                'payStatus'=>1,
                'receivable'=>0,
                'rewardFee'=>0,
                'currency'=>'CNY',
                'category'=>6,
                'totalWeight'=>$total_weight,
                'totalVolume'=>'',
                'totalQty'=>$total_quantity,
                'daySequence'=>$count
            ),
            'itemDetails'=>$order_goods,
            'send'=>array(
                'storeName'=>$transport_info['STORENAME'],
                'storeCode'=>$transport_info['STORECODE'],
                'addressProvince'=>$transport_info['ADDRESSPROVINCE'],
                'addressCity'=>$transport_info['ADDRESSCITY'],
                'addressDistrict'=>$transport_info['ADDRESSDISTRICT'],
                'address'=>$transport_info['ADDRESS'],
                'contacts'=>$transport_info['CONTACTS'],
                'mobile'=>$transport_info['MOBILE']

            ),
            'receive'=>array(
                'addressProvince'=>$province_name,
                'addressCity'=>$city_name,
                'addressDistrict'=>$district_name,
                'address'=>$receiver_address,
                'contacts'=>$order['consignee'],
                'mobile'=>$order['mobile']
            ),
        );

        $this->write_log("sf test data: ".json_encode($order_shipping_info),'sf_shipping');
        //推送订单
        $SF_Submit = new SfshippingSubmit();
        $res = $SF_Submit->order_service($order_shipping_info);

        $this->write_log("sf test: ".json_encode($res),'sf_shipping');

        if((empty($res) || $res['status']!='100')){
            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")出仓失败，".$res['message'],array(),array(),false);
            if($show_return){
                returnApiError("顺丰配送订单推送不成功，订单(".$order['order_sn'].")出仓失败，".$res['message']);
            }else{
                $return_data['error'] = 1;
                $return_data['msg'] = "订单(".$order['order_sn'].")出仓失败，".$res['message'];
                return $return_data;
            }
        }else{
            $order_data = array(
                'shipping_extend_type'=>'sf',
                'shipping_extend_status'=>0
            );
            M("order_info")->where(array('order_id'=>$order['order_id']))->save($order_data);

            $shipping_extend_order_id = $res['sfOrderNo'];
            $this->save_shipping_extend_order_id($order['order_id'],$shipping_extend_order_id);
        }

        return true;
    }

    /**
     * @param $order_id
     * @param $order_info
     * @param $user_id
     * @param bool $show_return
     * @return bool
     */
    public function send_order_to_sdx($order_id,$order_info,$user_id,$show_return=true){
        if(empty($order_info) && !empty($order_id)){
            if($show_return){
                returnApiError('配送订单不存在');
            }
        }
        if(empty($order_info)){
            $where['order_id'] = $order_id;
            $order_info = M("order_info")
                ->field("order_sn,consignee,mobile,province,city,district,address,longitude,latitude,sign_building,best_time_start,best_time,postscript,address_name,wid,wdr_id,distribution_company_id,station,shipping_extend_status")
                ->where(array("order_id"=>$order_id))->find();
        }
        if(empty($order_info)){
            return false;
        }
        $data = array();

        //获取取货点配置信息
        $sdx_bsc_config = C('SDX_BSC_CONFIG');

        //$sdx_chucang_user_list = C('sdx_chucang_user_id');
        //$sdx_warehouse_list = array_flip($sdx_chucang_user_list);
        //$wid = $sdx_warehouse_list[$user_id];

        $pickup_point_list = $sdx_bsc_config['WAREHOUSE'];
        $pickup_point_info = $pickup_point_list[$order_info['wid']];
        //设置取货点id
        $data['scc_id'] = $pickup_point_info['scc_id'];

        $data['third_sn'] = $order_info['order_sn'];    //订单号
        $data['consignee'] = $order_info['consignee'];   //收货人姓名
        $data['mobile'] = $order_info['mobile'];      //手机号
        $data['province'] = M('region')->where(array('region_id'=>$order_info['province']))->getField('region_name');    //省份
        $data['city'] = M('region')->where(array('region_id'=>$order_info['city']))->getField('region_name');        //城市
        $data['district'] = M('region')->where(array('region_id'=>$order_info['district']))->getField('region_name');    //区县
        $data['address'] = $order_info['address'].$order_info['address_name'];     //详细地址

        if($order_info['longitude']>$order_info['latitude']){
            //$data_gps =GCJ02_To_BD09($order_info['longitude'],$order_info['latitude']);
            $longitude = $order_info['latitude'];
            $latitude = $order_info['longitude'];
        }else{
            //$data_gps =GCJ02_To_BD09($order_info['latitude'],$order_info['longitude']);
            $longitude = $order_info['latitude'];
            $latitude = $order_info['longitude'];
        }


        $data['longitude'] = $longitude;   //经度
        $data['latitude'] = $latitude;    //纬度

        $data['landmarks'] = $order_info['sign_building'];   //地标
        $data['delivery_start_time'] = $order_info['best_time_start']; //开始配送时间
        $data['delivery_end_time'] = $order_info['best_time'];   //结束配送时间
        $data['remark'] = $order_info['postscript'];   //订单备注

        $_POST['store'] = 1;
        $goods_list = A('Bsc')->get_goods_list_real($order_info['order_id']);

        //订单商品数量
        //$order_bag = S('order_bag_'.$order_info['order_id']);
        $k3cn_sn = M("order_info")->where(array("order_id"=>$order_info['order_id']))->getField("k3cn_sn");
        if(empty($k3cn_sn)){
            $order_bag = S("order_bag_".$order_info['order_id']);
        }else{
            $order_bag = $this->newGetS("order_bag_".$order_info['order_id']);
        }
        //$order_bag = $this->newGetS('order_bag_'.$order_info['order_id']);
        if(!empty($order_bag)){
            $order_goods = array();
            foreach ($order_bag as $order_item){
                $tmp_order_item = array();
                $type_name = $this->get_bag_type_name($order_item['type']);
                $tmp_order_item['goods_name'] =$type_name.$order_item['current'];
                $tmp_order_item['goods_price'] =0;
                $tmp_order_item['goods_sn'] =$order_info['order_sn'].str_pad($order_item['all'],2,"0",STR_PAD_LEFT).str_pad($order_item['current'],2,"0",STR_PAD_LEFT).$order_item['type'];
                $tmp_order_item['goods_number'] =1;
                $tmp_order_item['goods_weight'] =1;
                $order_goods[] = $tmp_order_item;
            }
            $order_weight = 0;
            foreach ($goods_list as $key=>$value){
                $order_weight += $value['goods_weight']*$value['goods_number'];
            }

            $data['order_weight'] = $order_weight;   //订单重量指定
            $data['goods_num'] = count($order_goods);    //订单商品袋数

            $data['goods'] = $order_goods;
        }else{
            $data['goods'] = $goods_list;
        }

        $data['order_freight'] = $this->get_order_freight($order_info['wdr_id'],$order_info['distribution_company_id'],$order_weight);

        if($order_info['shipping_extend_status']==8){
            $data['repush_order'] = 1;
        }

        $sdx_bsc = new SdxbscSubmit();
        $post_value_array = $sdx_bsc->post_order($data);
        if($post_value_array['status']==1){
            //成功推送至BSC
            $order_data = array(
                'shipping_extend_type'=>'sdx',
                'shipping_extend_status'=>0,
                'push_bsc'=>2
            );
            M("order_info")->where(array('order_id'=>$order_info['order_id']))->save($order_data);

            $this->save_shipping_extend_order_id($order_info['order_id'],$post_value_array['order_sn']);

            $this->write_log($order_info['order_sn'],'sdx_bsc_ok');
            return true;
        }else{
            //推送至BSC失败
            $this->write_log($order_info['order_sn']." CODE:".$post_value_array['err_code']." msg:".$post_value_array['error_msg'],'sdx_bsc_fail');
            if($show_return){
                returnApiError("食得鲜配送订单推送不成功，订单(".$order_info['order_sn'].")出仓失败，".$post_value_array['error_msg'].$data_gps['latitude'].$data_gps['longitude']);
            }else{
                $return_data['error'] = 1;
                $return_data['msg'] = "订单(".$order_info['order_sn'].")出仓失败，".$post_value_array['error_msg'];
                return $return_data;
            }
        }
    }

    /**
     * 计算运费
     * @param $wdr_id
     * @param $distribution_company_id
     * @param $goods_weight
     * @return int
     */
    public function get_order_freight($wdr_id,$distribution_company_id,$goods_weight){
        $distribution_cost = 0;
        $company_area = M('distribution_company_area')->where(array('area_id'=>$wdr_id,'company_id'=>$distribution_company_id))->find();
        $first_heavy = $company_area['first_money'];
        $continued_heavy = $company_area['continue_money'];

        $company_info = M('distribution_company')->where(array('id'=>$distribution_company_id))->find();

        if(!empty($company_area) && !empty($company_info) && $goods_weight>0){
            if(!empty($continued_heavy)){
                if($goods_weight>$company_info['first_num']){
                    //首重费用和续重费用
                    $goods_weight_ext = $goods_weight-$company_info['first_num'];
                    $distribution_cost = $first_heavy+$continued_heavy*($goods_weight_ext/$company_info['continue_num']);
                }else{
                    //仅首重费用
                    $distribution_cost = $first_heavy;
                }
            }else{
                $distribution_cost = $first_heavy;
            }
        }
        return $distribution_cost;
    }

    /**
     * 获取订单退款商品数量
     * @param $order_id
     * @param $goods_id
     * @return int
     */
    public function get_goods_refund_num($order_id,$goods_id){
        $sum_refund_number = M('refund_detail')->where(array('order_id'=>$order_id,'goods_id'=>$goods_id))->sum('refund_number');
        if(empty($sum_refund_number)){
            $sum_refund_number = 0;
        }
        return $sum_refund_number;
    }

    /**
     * @param $order_sn
     * @param string $tip
     * @param int $length
     * @return string
     */
    private function get_repush_order_sn($order_sn,$tip='gk',$length=5){
        $str='0123456789';
        $rndstr ='';
        for($i=0;$i<$length;$i++){
            $rndcode=rand(0,9);
            $rndstr.=$str[$rndcode];
        }
        return $order_sn.$tip.$rndstr;
    }

    public function write_log($message,$filename){
        $log = new Log();
        $destination = C('LOG_PATH').date('y_m_d').'_'.$filename.'.log';

        $log->write($message,'DEBUG','',$destination);
    }


    /**
     *todo 获取推送错误信息
     * @param $code
     * @return string
     */
    private function get_gk_error_msg($code){
        $msg =  array(
            '0x0001'=>'无效的API（系统级）',
            '0x0002'=>'无效的会话密钥（系统级）',
            '0x0003'=>'请求已超时（系统级）',
            '0x0004'=>'无效的签名（系统级）',
            '0x0005'=>'权限错误（系统级）',
            '0x0006'=>'服务不可用（系统级）',
            '0x0010'=>'无效的参数（系统级）',
            '0x1001'=>'权限错误（用户级）',
            '0x1002'=>'无效的参数（用户级）',
            '0x1003'=>'无效的验证码（用户级）',
            '0x1004'=>'版本过低（用户级）',
            '0x2001'=>'超出服务区月',
            '0x2002'=>'超出配送距离',
            '0x2003'=>'附近没有活动快递员',
            '0xFFFF'=>'未知错误'
        );

        if(empty($msg[$code])){
            return '未知错误';
        }else{
            return $msg[$code];
        }
    }

    /**
     * todo 修改订单为配送单
     */
    public function change_order_to_distribution(){
        $shipping_time      = I("post.shipping_time");  //配送时间
        $user_id      = I("post.user_id");  //配送时间
        $order_id = I("post.order_id");  //配送时间
        $consignee=I('post.consignee');
        $mobile=I('post.mobile');
        $province=I('post.province');
        $city=I('post.city');
        $district=I('post.district');
        $address=I('post.address');
        $sign_building = I ('post.sign_building');


        $shipping_time = explode("-",$shipping_time);
        $get_fac = D('Useraddress')->check_serve_by_address($province.$city.$district.$address,$sign_building);
        $data['consignee'] = $consignee;
        $data['province'] = D('Useraddress')->get_address_id($province, 1);;
        $data['city'] = D('Useraddress')->get_address_id($city, 2);;
        $data['district'] = D('Useraddress')->get_address_id($district, 3);
        $data['address'] = $address;
        $data['mobile'] = $mobile;
        $data['sign_building'] = $sign_building;
        $data['shipping_id'] = 3;
        $data['sorting_id'] = 431;
        $data['best_time_start'] = $shipping_time[0];
        $data['best_time'] = $shipping_time[1];
        $data['order_status'] = 5;
        $data['shipping_status'] = 5;
        $data['wid'] = $this->get_user_wid_identity($user_id);
        $data['wdr_id'] = $get_fac['wdr_id'];
        $data['shipping_name'] = "送货到家 [ 由自提转 ]";

        if($get_fac['wdr_id']<0){
            returnApiError("未匹配到地址");
        }
        $re = M("order_info")->where(array("order_id"=>$order_id))->save($data);
        if($re){

            //订单操作日志
            $a=array(
                'order_id'=>$order_id,
                'user_id'=>$user_id,
                'order_status'=>5,
                'pay_status'=>M("order_info")->where(array("order_id"=>$order_id))->getField("pay_status"),
                'shipping_status'=>5,
                'to_user'=>1,
                'action_note'=>'由自提单转配送单'
            );
            A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
            A("Distribution")->record_logistics($order_id,5,"送货到家 [ 由自提转 ]");
            returnApiSuccess(null,"已转变成功");
        }else{
            returnApiError("错误");
        }


    }

    /**
     * todo 根据地址获取配送时间
     */
    public function get_distribution_time_by_address(){
        $address = I("post.address");          //地址
        $sign_building = I("post.sign_building");          //地址
        $get_fac = D('Useraddress')->check_serve_by_address($address,$sign_building);
        if($get_fac['name']<0){
            returnApiError("此地址超出配送区域");
        }
        $distributie_time = D("Users")->distributie_time_list_new($get_fac['mode_id'],$get_fac['wdr_id']);
        if(count($distributie_time['tomorrow'])>0){
            returnApiSuccess($distributie_time,"配送时间已返回");
        }else{
            returnApiError("请编辑详细地址");
        }

    }


    /**
     * todo 商品质检确认
     */
    public function confirm_quality_goods(){
        $user_id      = I("post.user_id");  //配送时间
        $order_id = I("post.order_id");  //配送时间
        $order_model = M("order_info")->
        field("pay_status,shipping_status,pay_status,order_status")->
        where(array(
            "order_id"=>$order_id,
            "order_status"=>array("neq",2),
            "k3cn_sn"=>array("EXP","IS NULL"),
            "freeze_status"=>0
            //"196_admin_id"=>0
        ))->find();
        if(empty($order_model)){
            returnApiError("此单为金蝶订单，请使用新版处理");
        }
        if($order_model['shipping_status']==5){
            if($order_model['pay_status']>1){
                $KingdeeService = new KingdeeService();
                $KingdeeJosn = $KingdeeService->checkSalesOrder($order_id);
                $KingdeeArray = json_decode($KingdeeJosn,true);
                if($KingdeeArray['code']==200){
                    $order_change = M("order_info")->where(array("order_id"=>$order_id))
                        ->save(array("quality_id"=>$user_id,"quality_time"=>gmtime()));
                    if($order_change){
                        $a=array(
                            'order_id'=>$order_id,
                            'user_id'=>$user_id,
                            'order_status'=>$order_model['order_status'],
                            'shipping_status'=>$order_model['shipping_status'],
                            'pay_status'=>$order_model['pay_status'],
                            'to_user'=>1,
                            'action_note'=>'商品质量已确认'."Kingdee SN:".$KingdeeArray['data']['Number']
                        );
                        A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
                        A("Distribution")->record_logistics($order_id,$order_model['shipping_status'],"商品质量已确认");//记录日志
                        returnApiSuccess(null,"确认成功");
                    }
                }else{
                    returnApiError("金蝶返回错误信息:\n".$KingdeeArray['message']);
                }


            }else{
                returnApiError("订单还未支付");
            }
        }else{
            returnApiError("订单需要配货完成/已取消/需处理问题单");
        }
    }
    /**
     * todo 获取默认订单原因
     */
    public function get_order_action_reason(){
        $data['order_reason'] = C("order_reason");
        $data['goods_reason'] = C("goods_reason");
        $data['shipping_reason'] = C("shipping_reason");
        returnApiSuccess($data);
    }

    /**
     * 订单分袋数
     */
    public function order_bag(){
        $order_id = I("post.order_id");     //订单ID
        $bag_num = I("post.bag");           //总袋数
        $bag_type = I("post.bag_type");           //分袋数加常温方式

        $order_info = M("order_info")->field("k3cn_sn,order_status,shipping_status,pay_status")
            ->where("order_id = ".$order_id)->find();
        if(!empty($order_info['k3cn_sn'])){
            returnApiError("此单请用新客户端操作");
        }
        //3,0,3 常温/冷冻/冷藏
        $type_name = array("常","冻","藏");
        if(empty($bag_type)){
            $str= "老版本客户端，无记录";
        }else{
            $str= "";
            $order_bag_info = array();
            $bag_array = explode(",",$bag_type);
            $current_num = 1;
            foreach ($bag_array as $key=>$value){
                if($key==1){
                    $type = 2;
                }elseif($key==2){
                    $type = 1;
                }else{
                    $type = $key;
                }
                if($value>0){
                    for($i=0;$i<$value;$i++){
                        $bag_one_info = array(
                            "all"=> $bag_num,
                            "current"=> $current_num,
                            "type"=> $type,  //常温0 冷藏1 冷冻2
                            "is_scan"=> 0
                        );
                        $current_num ++;
                        $order_bag_info[] = $bag_one_info;
                    }
                }
                $str .=$type_name[$key].$value;
            }
            if($order_bag_info){
                S("order_bag_".$order_id,$order_bag_info,2592000);  //订单分袋信息保存一个月
            }
        }
        $add['order_id'] = $order_id;
        $add['bag_num'] = $bag_num;



        $order_model = M("order_info_ext")->add($add,$options=array(),$replace=true);
        if($order_model){
            $a=array(
                'order_id'=>$order_id,
                'user_id'=>I('post.user_id'),
                'order_status'=>$order_info['order_status'],
                'shipping_status'=>$order_info['shipping_status'],
                'pay_status'=>$order_info['pay_status'],
                'to_user'=>1,
                'action_note'=>'打印质检单，总数：'.$bag_num.", ".$str
            );
            //dump($a);
            A("Distribution")->record_diliveryman_log($a);
            A("Distribution")->record_logistics($order_id,$order_info['shipping_status'],'打印质检单，总数：'.$bag_num.", ".$str);
            returnApiSuccess(null,"OK");
        }else{
            returnApiError("失败");
        }
    }

    /**
     * 取消需回仓
     */
    public function cancel_back_wdr(){
        $order_str = I("post.order_id");
        $user_id      = I("post.user_id");  //
        if(!is_numeric($order_str)){
            returnApiError('订单ID为空/仅支持单个订单');
        }
        $where['outgo'] = 2;
        //$where['196_admin_id'] = 0;
        $where['order_id']=$order_str;
        $where['order_status']=array("neq",2);


        $order_one=M('order_info')->field('order_id,order_status,shipping_status,order_sn,pay_status')->where($where)->find();
        if ($order_one) {
            $data['outgo'] = 1;             //已出仓
            $data['station'] = 1;           //已到站
            $data['shipping_status'] = 5;   //配货完成
            $data['sorting_id'] = $user_id;
            $data['sorting_time'] = gmtime();
            $data['station_id'] = $user_id;
            $data['station_time'] = gmtime();
            $id = M('order_info')->where(array("order_id"=>$order_str))->save($data);
            if ($id != false) {
                $a=array(
                    'order_id'=>$order_str,
                    'user_id'=>I('post.user_id'),
                    'order_status'=>$order_one['order_status'],
                    'shipping_status'=>$order_one['shipping_status'],
                    'pay_status'=>$order_one['pay_status'],
                    'to_user'=>1,
                    'action_note'=>'取消需回仓'
                );
                A("Distribution")->record_diliveryman_log($a);
                $flag = $this->send_order_to_sdx($order_str,'',$user_id,false);
                returnApiSuccess(array('id'=>$id),'取消需回仓成功','取消需回仓成功');
            } else {
                returnApiError('取消需回仓失败，再试一次');
            }
        }else{
            returnApiError("此订单不在需回仓状态");
        }
    }

    /**
     * 获取质检列表
     */
    public function quality_log(){
        $user_id=I('post.user_id','intval');

        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);

        $page=I('post.page','intval');
        $year = I('post.year','intval');
        $month = I('post.month','intval');
        if($year>0 && $month>0){
            $days = date('t', strtotime($year."-".$month));
            $begintime = strtotime($year."-".$month."-1");
            $endtime = strtotime($year."-".$month."-".$days." 23:59:59");
            $where['quality_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ; //
        }
        $company_array = M("distribution_company_user")->where(array("user_id"=>$user_id))->getField("company_id",true);
        if(!empty($company_array)){
            $where['distribution_company_id'] = array("in",$company_array);
        }

        $where['quality_id']=$user_id;

        $count=M('order_info')->where($where)->count();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('order_info')->field('distribution_company_id,shipping_id,quality_id,quality_time,address_id,user_id,batch_no,outgo,sorting_id,wp_userid,wid,wdr_id,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('sorting_time desc,order_id desc')->select();
        if($list){
            $push_array = array();
            foreach ($list as $k=>$v){
                unset($one_order);

                $one_order = $this->get_order_info($v);
                $one_order['order_state'] = 2;  //配货中
                $one_order['quality_time'] = $v['quality_time']+3600*8;
                if($v['quality_id']>0){
                    $one_order['isCheck'] = 1;
                }else{
                    $one_order['isCheck'] = 0;
                }
                $re_goods_list = $this->re_goods_list($v['order_id'],$wid);
                if($re_goods_list){
                    $one_order['goods_list_back']=$re_goods_list;
                }
                $goods_list = $this->sh_goods_list($v['order_id'],$wid);
                if($goods_list){
                    $one_order['goods_list']=$goods_list;
                }
                $cold_data = $this->check_goods($goods_list);
                $one_order['is_cold'] = $cold_data['is_cold'];
                $one_order['is_ice'] = $cold_data['is_ice'];
                $one_order['is_nom'] = $cold_data['is_nom'];
                array_push($push_array,$one_order);
                unset($one_order);
            }
            returnApiSuccess(array('list'=>$push_array,'is_last'=>$is_last,'count'=>$count),'success');
        }else{
            returnApiError("已返回全部");
            $list = array();
            $is_last =1;
            $count = 0;
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }
    }

    /**
     * 概览出仓订单情况
     */
    public function getMyOrderOverviewChuCang(){

        //本日
        $startTime=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endTime=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $data['todayNum'] = $this->gerCompleteOrderNumByDate($startTime,$endTime);


        //本周完成订单数
        $startTime=mktime(0,0,0,date('m'),date('d')-date('w')+1,date('Y'));
        $endTime=mktime(23,59,59,date('m'),date('d')-date('w')+7,date('Y'));
        $data['weekNum']=$this->gerCompleteOrderNumByDate($startTime,$endTime);

        //本月完成订单数
        $startTime=mktime(0,0,0,date('m'),1,date('Y'));
        $endTime=mktime(23,59,59,date('m'),date('t'),date('Y'));
        $data['monthNum']=$this->gerCompleteOrderNumByDate($startTime,$endTime);

        $data['allNum']=$this->gerCompleteOrderNumByDate();



        returnApiSuccess($data,"个人出仓订单概览信息已返回");
    }

    /**
     * 根据时间段获取配送完成订单数
     * @param null $startTime
     * @param null $endTime
     * @return mixed
     */
    public function gerCompleteOrderNumByDate($startTime=null, $endTime=null){
        $user_id=I('post.user_id','intval');
        $where =array();
        $where['outgo_id'] = $user_id;         //出仓员ID
        $where['outgo'] = 1;                   //已出仓
        $where['pay_status']=array('in','2,3');
        $where['order_status']= array('neq',2);
        $where['196_admin_id']= 0;

        if(!empty($startTime)&&!empty($endTime)){
            $where['outgo_time']    = array(
                array('gt',$startTime-28801),
                array('lt',$endTime-28799)
            );      //出仓时间
        }
        return M('order_info')->where($where)->count();
    }
}